2

Possible Duplicate:
Scanner issue when using nextLine after nextInt

In the following two code snippets, I first ask for the number of inputs required and let the user input that many inputs of a particular kind. When the required inputs are String types, it takes one less input unless I use s.next() first, while for Integers it works fine. I don't understand why. Can someone please explain?. Thanks

First Code with String inputs and nextLine function:

public static void main(String args[]){

    Scanner s = new Scanner(System.in);

    int num =  s.nextInt();

    String[] inputs = new String[num];

    for (int i = 0; i < inputs.length; i++) {
        inputs[i]=s.nextLine();
    }
    System.out.println("end of code");
}

Second Code with Integer inputs and nextInt function:

public static void main(String args[]){

    Scanner s = new Scanner(System.in);

    int num =  s.nextInt();

    Integer[] inputs = new Integer[num];

    for (int i = 0; i < inputs.length; i++) {
        inputs[i]=s.nextInt();
    }
    System.out.println("end of code");
}
Community
  • 1
  • 1
Shimano
  • 785
  • 1
  • 6
  • 13

1 Answers1

0

It is because of the following line:

int num =  s.nextInt();

Your next INT only returns the INT until it gets to the \n character.

If you had a test file like this:

4
1
2
3
4

Your character code will look like this:

4'\n'
1'\n'
2'\n'
3'\n'
4'\n'

So when you grab the integer, it will grab the 4 for your "nextInt()" method on the scanner. When you tell it to grab the next line "nextLine()", it will grab the remainder of that line which is just '\n' and store nothing into the first value into your array.

On the reverse side, if you tell it to grab the next integer "nextInt()", it will search until it finds the next integer, which will cause the 1 to go into the first value into the array.

Clark Kent
  • 1,178
  • 1
  • 12
  • 26