【问题标题】:How to fix "NoSuchElementException" being thrown如何修复“NoSuchElementException”被抛出
【发布时间】:2019-09-28 03:03:05
【问题描述】:

我创建了一个交互式类来解决运动学方程问题(在用户输入循环中的另一个类中访问:mathiverse),它工作得很好,但在给出答案后它会抛出一个NoSuchElementException

我尝试移动我关闭扫描仪的位置,但没有奏效,我很确定问题在于我的 Kinematic 类在我的输入循环中的功能。

我的用户输入循环和运动构造函数(不在同一个类中):

while(!(input.equals("exit")))
{
    if(input.equals("help"))
    {
        System.out.println("~ Commands ~");
        System.out.println("help - brings up a list of 
        commands(what you're reading)");
        System.out.println("kinematic - solves a kinematic 
        equations problem; requires input of known and unknown 
        variables");
        System.out.println("exit - closes the program");
        System.out.println("~~~~~~~~~~~~");
    }

    //user decides to explore kinematic options
    if(input.equals("kinematic"))
    {
        Kinematic calc = new Kinematic();

        System.out.println(calc.answer());
    }

    input = scan.nextLine();
}

public Kinematic()
{
    Scanner scanMath = new Scanner(System.in);

    System.out.println("If you are solving for the variable, enter \"?\", 
    if the variable is not given, enter a space.");
    System.out.println("Enter the acceleration: ");
    acc = scanMath.nextLine();

    System.out.println("Enter the displacement: ");
    disp = scanMath.nextLine();

    System.out.println("Enter the initial velocity: ");
    init = scanMath.nextLine();

    System.out.println("Enter the final velocity: ");
    fin = scanMath.nextLine();

    System.out.println("Enter the time: ");
    time = scanMath.nextLine();

    scanMath.close();
}

给出答案后,我希望我的代码继续搜索输入,但它会抛出此消息:

线程“主”java.util.NoSuchElementException 中的异常:没有行 在 java.base/java.util.Scanner.nextLine(Scanner.java:1651) 中找到 Mathiverse.main(Mathiverse.java:53)

【问题讨论】:

    标签: java nosuchelementexception


    【解决方案1】:

    从 Kinematic 关闭扫描仪时,您也会关闭 System.in 流。在您的主要方法和运动学中使用相同的扫描仪。

    看看: java.util.NoSuchElementException - Scanner reading user input

    【讨论】:

      猜你喜欢
      • 2017-02-25
      • 1970-01-01
      • 2016-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-25
      相关资源
      最近更新 更多