Why is first for loop iteration skipped?

后端 未结 5 2154
粉色の甜心
粉色の甜心 2021-01-26 10:57

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) {

         


        
相关标签:
5条回答
  • 2021-01-26 11:10
        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];
    
    0 讨论(0)
  • 2021-01-26 11:15

    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;
    }
    
    0 讨论(0)
  • 2021-01-26 11:19

    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.

    0 讨论(0)
  • 2021-01-26 11:22

    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.

    0 讨论(0)
  • 2021-01-26 11:32

    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 #.

    0 讨论(0)
提交回复
热议问题