0

I'm building a project where I will take three inputs from the users: name,ID,GPA. the users should enter them in one line separated by a semicolumn";" and I want to be able to receive them as one line and be able to save them in three variables. I'm applying a method where I will take three variables from the user. for example : the user will enter the name,Id and GPA like this:

1;Sally;90.5;       //in one line separated by ";"

I want to be able to save each info from the user in different variable. Can someone tell me how will I be able to implement that?

Here is the method:

private static void addNewStudent() {
    System.out.println("enter ID;Name;Gpa; ");
    String info = scanner.nextLine();

Note: I'm trying the apply the CSV in my project.

sally
  • 13
  • 5

2 Answers2

1

You just need read one line and then split it into string array.The input order must be ID -> NAME -> GPA:

    private static void addNewStudent() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("enter ID;Name;Gpa; ");
        String info = scanner.nextLine();
        if (info != null) {
            String[] infoArray = info.split(",");
            if (infoArray.length == 3) {
                String id = infoArray[0];
                String name = infoArray[1];
                String gpa = infoArray[2];
            }
        }
    }
TongChen
  • 1,414
  • 1
  • 11
  • 21
0

This should do to split the input by ";":

String[] input = GPA.split[";"];

Before trying to get the values, check if the input array has the expected size.

papalulu
  • 78
  • 6