0

I am running this code snippet:

    personalInfo[] pers = new personalInfo[3];
    Scanner input = new Scanner(System.in);

    String inName;
    String inAddress;
    int inAge;
    long inPhoneNumber;

    for(int i=0; i<3; i++){
        pers[i] = new personalInfo();
        System.out.printf("Please input the name for person %d: ", i );
        inName = input.nextLine();
        pers[i].setName(inName);
        System.out.printf("Please input the address for person %d: ", i );
        inAddress = input.nextLine();
        pers[i].setAddress(inAddress);
        System.out.printf("Please input the age for person %d: ", i );
        inAge = input.nextInt();
        pers[i].setAge(inAge);
        System.out.printf("Please input the phone number for person %d, without dashes included (ex. 1112223333): ", i );
        inPhoneNumber = input.nextLong();
        pers[i].setPhoneNumber(inPhoneNumber);
    }

I get this output:

Please input the name for person 0: name
Please input the address for person 0: address
Please input the age for person 0: 18
Please input the phone number for person 0, without dashes included (ex. 1112223333): 1289308439
Please input the name for person 1: Please input the address for person 1: 

You can see that on the first iteration of the loop it prompts for name, waits for input, then prompts for address. However, on the second iteration of the loop it prompts for name and address on the same line, then waits for input. This doesn't make sense to me. Can anyone please explain this for me?

Rick
  • 41
  • 6
  • I realize I used the wrong format parameters with printf, but I corrected this and it is not what is causing the problem. – Rick Apr 18 '16 at 06:54
  • add `input.nextLine()` at the end of loop – singhakash Apr 18 '16 at 06:56
  • That works, but can you please explain why? – Rick Apr 18 '16 at 07:06
  • when using netxtLine(), cursor goes to the next line, but for nextLong() its not. Per @singhakash adding that will work, and convert the same to long value from string. Checkout the api for more documentation. – Kartik Narayana Maringanti Apr 18 '16 at 07:11
  • Just so I'm clear, nextInt() consumes the newline, but nextLong() does not? – Rick Apr 18 '16 at 07:15
  • `nextLine()` consume the whole line `next()`,`nextInt()`,`nextLong()` etc consume a token so suppose input is `2 3 1` and you are doing `String a = input.nextLine()` the value of `a` will be `2 3 1`(reads whole line) and if you do `int a = input.nextInt()` the value of a is `2`(reads a token seperated by space). So in your above code `nextLong()` consumes the token and rest of the line is left so the second iteration of loop `nextLine()` consumes the leftover of `nextLong()` and moves to second `nextLine()`. Check the dupe answer for more info. – singhakash Apr 18 '16 at 07:16

0 Answers0