1
import java.util.Scanner;

public class test{

 public static void main(String[] args)
 {
 Scanner input = new Scanner(System.in);
 System.out.println("Enter maximum number : ");
 int items = input.nextInt();
 String arr[] = new String[items]; 
int x = 0;
 while(x < items)
 {

    System.out.println("Enter item  " + x + ":");
    arr[x] = input.nextLine();
    x++;
  }
}
}

On my code, First is I asked maximum number in an array index and store to arr[]. Now, I find error when I press enter and it displayed "Enter item 0" and "Enter item 1". It displayed index arr[1] . What should be displayed is "Enter item 0" only at my first press of enter. Does anybody know about this?

Thanks

smz
  • 31
  • 2
  • 6
  • Do you have any other alternative code for this problem? thanks – smz Dec 04 '13 at 03:42
  • Why don't you ask yourself "Why is my While-Loop running two times?". The answer to that is due to what ever items originally is. – Tdorno Dec 04 '13 at 03:43
  • Take a look here http://stackoverflow.com/questions/5032356/using-scanner-nextline. `nextInt` does not read the EOL, that's why it's picked up by subsequent call to `nextLine`. – denis.solonenko Dec 04 '13 at 03:48

1 Answers1

3

The problem is that the nextInt() Scanner method does not handle the end of line (EOL) token, and so it is left dangling when you call input.nextInt() only to be snarfed up when you call input.nextLine() which does handle the EOL token.

One solution is to call nextLine() explicitly to handle the dangling token and to allow the Scanner to be ready for your next full line of input:

int items = input.nextInt();
input.nextLine(); // add this

When you create a line of text and press <enter>, an extra 1-2 characters are appended to the end of your text. A common one is called line feed, or LF, which is represented by numerically as decimal 10, and by a char of \n, and another one is called carriage return, or CR, and is represented numerically as 13, and char-wise as \r. Unix and Apple OS systems usually append just the LF while Windows/DOS systems append LF and CR together.

If you call input.nextInt() on a line of text, the Scanner will grab the int text, but will not grab the end of line tokens or chars mentioned above, and these characters will be left dangling or unhandled. If you you call input.nextInt() and there is more numeric input on the next line, then the Scanner will skip over the EOL tokens and get the number text, but if you call input.nextLine() the Scanner will grab the EOL tokens and nothing else.

Hovercraft Full Of Eels
  • 276,051
  • 23
  • 238
  • 346
  • thank you so much. I got your point. Anyway, what do you mean by left dangling? – smz Dec 04 '13 at 05:07