首页 > 解决方案 > 无法使用扫描仪接受多个输入

问题描述

我正在编写 java 代码以将来自用户的输入分配给三个变量(类型为 double、string、int)。我为此使用了扫描仪。它编译并运行完美,没有任何错误。

我的问题:
我只能向 double 类型的变量(第一个变量)输入一个。我无法为其他两个变量输入值。你能解释为什么会发生这种情况并为我解决这个问题吗?

public class Main {

    public static void main(String[] args) {
        double revenueTill;
        String month;
        int dayOfMonth;
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter revenue until now: ");
        revenueTill = scanner.nextDouble();

        System.out.println("Enter month: ");
        month = scanner.nextLine();

        System.out.println("Enter day of month: ");
        dayOfMonth = scanner.nextInt();

        MonthPrediction monthPrediction = new MonthPrediction(revenueTill, month, dayOfMonth);
        monthPrediction.showRevenueOfMonth(revenueTill, month, dayOfMonth);
    }
}

标签: javaintellij-ideainput

解决方案


尝试将 nextLine() 更改为 next():

System.out.println("Enter month: ");
month = scanner.next();

System.out.println("Enter day of month: ");
dayOfMonth = scanner.nextInt();

推荐阅读