0

I'm trying to get n lines of input (Strings) from the user

  • The n is set first
  • I initialize an array of Strings to save the input and for loop to save them.

The problem is that it always falls short meaning

  • if n=1 the program is terminated
  • if n=2 it takes only 1 input
  • if n=3 it takes only 2 inputs and so on ......

What is wrong ?

Scanner sc = new Scanner(System.in);
//how many lines should be taken
int lines = sc.nextInt(); 
// initialize input array
String[] longWords = new String[lines] ;

//set the input from the user into the array
for (int i = 0; i < longWords.length; i++) {
    longWords[i] = sc.nextLine() ;
}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Hossam
  • 15
  • 1
  • 4

2 Answers2

3

Do it like this:

Scanner sc = new Scanner(System.in);
//how many lines should be taken
int lines = sc.nextInt(); 

//read the carret! This is, the line break entered by user when presses Enter
sc.nextLine();

// initialize input array
String[] longWords = new String[lines] ;

//set the input from the user into the array
for (int i = 0; i < longWords.length; i++) {
    longWords[i] = sc.nextLine() ;
}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
0

The issue is that nextInt() does not process the newline character at the end of a line of input, so when you enter 1 for instance, Scanner sees '1, '\n', but only takes in the '1'. Then when you call nextLine(), it sees the newline character left over and then immediately returns. It's a hard error to find, but just always remember whether or not the newline character is still waiting to be processed.

jackarms
  • 1,343
  • 7
  • 14