views:

72

answers:

2

What I want to do is ask the user for a number of strings to read into an array, and then ask the user to input that number of strings and read them into the array. When I run this code it never asks me for an input the first cycle of the first for-loop, just prints out "String #0: String #1: " and then I can input text. Why is that and what did I do wrong?

import java.util.Scanner;

public class ovn9 
{
public static void main(String[] args)
{
 Scanner sc=new Scanner(System.in);

 System.out.print("Number of inputs: ");

 int lines= sc.nextInt();
 String[] text=new String[lines];

 for(int x=0; x<text.length; x++)
 {
  System.out.print("String #"+x+": ");
  text[x] = sc.nextLine();
 }

 for(int y=0; y<text.length; y++)
  System.out.println(text[y]);

}
}
+4  A: 

Buffering.

nextInt() does not consume the newline in the input buffer that was put there when you entered the number of inputs. In the iteration 0 of the for loop, there's already a line of input in the buffer and nextLine() can complete immediately and the program will wait for new input line only in iteration 1. To ignore the newline in the input, you can add just another nextLine() call before entering the for loop.

laalto
Well answered +1 :)
o.k.w
Thank you, that worked wonders. I think I understand what you mean although I'm not familiar with the input buffer.
Andreas
A: 

Maybe you should change your loop to use 'sc.next()'

for ( int x = 0; x < lines; x++ ) {
    System.out.print("String #" + x + ": ");
    text[x] = sc.next();
}

It can be explained by the Java API

String next(): Finds and returns the next complete token from this scanner.

String nextLine(): Advances this scanner past the current line and returns the input that was skipped.

nandokakimoto
This works for me, thanks for your answer.
Andreas