I am working on a simple Java Assignment: and i need to fill an array with string types, via interactive input?
1970-01-01 00:00:00 UTC
I am working on a simple Java Assignment: and i need to fill an array with string types, via interactive input?
Three answers:
2011-09-03 09:11:32 UTC
First, good job on your code! Nicely done! Try taking the i++ out of the for loop header and put it after your nextLine. Or, use a do-while, declaring your index outside of the loop .
Anza Power
2011-09-03 08:51:26 UTC
Does your Scanner receive any other input before you start reading the lines? could be you pressed Enter or something earlier in the program and the first time you do myScanner.nextLine() it reads the last thing you inputted...
Like for instance if before you start reading the lines you ask the user for a number:
System.out.println("Please enter the number of elements:");
int array_length = myScanner.nextInt();
Then (I think) the user inputs a number and presses enter, the scanner reads the number but also there is a character after that number which is the line break (when the user pressed enter that created a new line and line breaks are considered characters) and then when you call myScanner.nextLine() the Scanner reads all input up to the line break which is 0 charecaters.
The reason why this doesn't happen with numbers is because even though the Scanner is standing at the point right before the line break, when you ask it for another INTEGER it goes and SEARCHES for that integer so it skips over the line, but when you ask it for a String it doesn't have to search for it because anything could count as a string...
AnalProgrammer
2011-09-03 01:53:28 UTC
Your problem lies in the code before the for loop.
You are probably reading in an integer and that is leaving a newline character in the buffer.
Then in the for loop your first iteration is taking the newline as a character that has been input.
You need to flush the buffer just before the for loop.
So add something like this
String dummy = myScanner.nextLine();
Have fun.
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.