my code is yielding an unexpected result. It seems my for loop skips the first iteration and I don\'t understand why.
public static void main(String[] args) {
number = get.nextInt();
// if i enter 4 then it will 4\n and nextInt will take only 4
// and the \n will be taken as input by the getline.
get.nextLine();
//this will return the "" from ""\n . so adding this will solve your problem
family_array = new String[number];
What worked for me was instantiating a new Scanner
in each iteration:
for(int i = 0; i < number; i++)
{
System.out.println("Enter family member name: ");
Scanner loopGet = new Scanner(System.in);
family_name = loopGet.nextLine();
family_array[i] = family_name;
}
Currently your call to Scanner#nextInt is not consuming the newline character so it is being passed through to your first call of Scanner#nextLine
, therefore it does not block.
You will need to add
get.nextLine();
after calling nextInt
so that your first call to nextLine
will block for IO
.
Notice that blank line between 4 and 1?
4
//this is it
1
When you call get.NextInt() you'd not eating the whole line, just the next int. The empty rest of the line is eaten in your first loop iteration. Add a call to get.nextLine() after reading the int.
I am going to say it is because you still have a buffered CR/LF - so the first one is set to blank. Notice the blank line as you print your family names (numbers). That is your blank family name.
The keyboard input is a buffered stream - it has your 5, and it has a CR/LF (or perhaps just a LF, depending on your OS).
You probably want to get the LINE and then do a string.convert, atoi, system.convert (whichever one is for Java) to get the #.