-1

In this code I can get upto only 2 values instead of 3 input values. Why does it so? Please explain me.

Scanner input = new Scanner(System.in);
System.out.println("Enter how many string to get");
int size;
size = input.nextInt();
String arr[] = new String[size];

System.out.println("Enter strings one by one");
for(int i = 0; i < size; i++) {
    arr[i] = input.nextLine(); 
    System.out.println(i);
}
hata
  • 8,429
  • 5
  • 32
  • 57
Vignesh
  • 3
  • 1
  • What is your question exactly? – kevintjuh93 Sep 17 '15 at 13:21
  • 2
    possible duplicate of [Skipping nextLine() after using next(), nextInt() or other nextFoo() methods](http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods) – Codebender Sep 17 '15 at 13:22

3 Answers3

0

See the answer from this link , it explains in detail what you are experiencing: Using scanner.nextLine()

In short the first nextLine reads the rest of the line from your nextInt call.

Community
  • 1
  • 1
0

nextInt will get the integer from the input buffer and will leave the new line character in the buffer. So when you call nextLine after that, the new line character in the buffer will be returned. To fix this, add a nextLine after calling nextInt

Scanner input = new Scanner(System.in);
System.out.println("Enter how many string to get");
int size;
size = input.nextInt();

input.nextLine();//get the new line character and ignore it

String arr[] = new String[size];

System.out.println("Enter strings one by one");
for(int i = 0; i < size; i++) {
    arr[i] = input.nextLine(); 
    System.out.println(i);
}
shan1024
  • 1,322
  • 6
  • 17
0

Use input.nextInt() instead of input.nextLine(). nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

next() reads the input only till the space. It doesnt read the space between words.

riya
  • 23
  • 1
  • 5