线程中的异常" main" java.util.NoSuchElementException运行时错误

时间:2017-08-06 05:06:30

标签: java

我在面向对象编程方面非常糟糕,我需要帮助解决导致此运行时错误的原因。我知道它可能很简单,所以请不要因为我的无能而生我的气。我很感激你的时间。

以下是代码:

import static java.lang.System.out; 
import java.util.Scanner;

class FormulaMethods {
void Force() {

    double mass, acceleration, answer;
    Scanner input = new Scanner(System.in);

    out.println("You have chosen the F=MA (Find Force) Formula.");
    out.println("Enter Mass Value: ");
    mass = input.nextDouble();
    out.println("Enter acceleration value: ");
    acceleration = input.nextDouble();
    answer = mass * acceleration;
    out.printf("The Force of these given variables is: %lf", answer);
    }
}

import java.util.Scanner;
import static java.lang.System.out;

class FormulaCalculator {
    public static void main(String args[]) {
        Scanner choice = new Scanner(System.in);
        int formula = choice.nextInt();
        FormulaMethods form = new FormulaMethods();

    System.out.println("Welcome to the Physics Formula Calculator Tool!");
    System.out.println("Please choose the number for the formula you would like to calculate: ");
    switch (formula) {
        case 1:
            form.Force();
            break;

        default: 
            System.out.println("No such option even exists, dimwit.");
            break;
        }

    }
}

没有编译错误,但我确实得到了这个:

线程中的异常" main" java.util.NoSuchElementException

at java.util.Scanner.throwFor(Unknown Source)

at java.util.Scanner.next(Unknown Source)

at java.util.Scanner.nextInt(Unknown Source)

at java.util.Scanner.nextInt(Unknown Source)

在FormulaCalculator.main(FormulaCalculator.java:7)

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

由于Scanner类方法nextInt导致此异常,因为没有数据。首先使用Scanner类方法hasNext()检查数据是否可用。