Java:hasNextLine()在没有输入的情况下返回True

时间:2018-08-04 23:32:54

标签: java java.util.scanner

我对Java还是很陌生,在测试一些基本功能时,我遇到了一个返回True的.hasNextLine()方法,因此没有给用户输入输入的机会。这是我要实现的目标的简短示例:

package default_package;
import java.util.Scanner;

public class Test {

    static Scanner userInput = new Scanner(System.in);

    static String name;
    static int age;
    static String job;
    static double salary;

    public static void main(String[] args) {
        System.out.print("What is your name? ");
        if (userInput.hasNextLine()) {
            name = userInput.nextLine();
        }

        System.out.print("How old are you? ");
        if (userInput.hasNextInt()) {
            age = userInput.nextInt();
        }

        System.out.print("What is your job? ");
        if (userInput.hasNextLine()){
            job = userInput.nextLine();
            System.out.println("True"); //debugging
        }

        System.out.print("What is your hourly rate? ");
        if (userInput.hasNextDouble()) {
            salary = userInput.nextDouble();
        }

        System.out.println("Done!");
    }
}

前两个“可视块” / if语句按预期运行,并允许用户输入名称和年龄,但是该程序不允许用户键入作业,而是打印True。

我的输出

What is your name? adam
How old are you? 22
What is your job? True
What is your hourly rate? 3.20
Done!

预期产量

What is your name? adam
How old are you? 22
What is your job? [user types in job]
True
What is your hourly rate? 3.20
Done!

我在哪里出问题了,我该怎么做才能防止这种情况再次发生?

0 个答案:

没有答案
相关问题