Why is line 17 of this Java program not executed?

As an exercise in my java course at uni this morning, I had to write a small program to ask users to enter some details and print them back I have finished writing it, but I have a strange problem

Refer to the following codes:

import java.util.Scanner;

public class Scanner_Exercise
{
    public static void main (String[] args)
    {
        Scanner keyboardIn = new Scanner(system.in);

        int accountId;
        String accountName;
        float accountBalance;

        System.out.println("Account ID: "); //Line 13
        accountId = keyboardIn.nextInt(); //Line 14

        System.out.println("Account name: "); //Line 16
        accountName = keyboardIn.nextLine(); //Line 17

        System.out.println("Account balance: ");
        accountBalance = keyboardIn.nextFloat();
    }
}

When the program is running, skip line 17 (see note); Account Name: printed, but the user has no chance to enter information, as if the line of code had been commented out No errors were thrown The output is as follows:

However, if I switch lines 13 and 14 with 16 and 17, as shown below, the program runs normally and does not skip any lines

System.out.println("Account name: "); //Line 16
accountName = keyboardIn.nextLine(); //Line 17

System.out.println("Account ID: "); //Line 13
accountId = keyboardIn.nextInt(); //Line 14

Why skip line 17 in the first case instead of the second?

If it has some relevance, I use JDK 6 update 18 and textpad 5.3 one

Solution

Looking at Javadoc should tell you why

Scanner. Nextline () jumps to the end of the current line and returns anything it skips Since the user has entered some data, this function returns the rest of the input stream When you switch orders, it doesn't have any input yet. That's why you see it asking for input

Important parts:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>