Hossam
Hossam

Reputation: 15

getting input from user always falls short by 1

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

The problem is that it always falls short meaning

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() ;
}

Upvotes: 0

Views: 57

Answers (2)

jackarms
jackarms

Reputation: 1333

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.

Upvotes: 0

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

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() ;
}

Upvotes: 3

Related Questions