gpt4 book ai didi

java - 如何修复 "NoSuchElementException"被抛出的问题

转载 作者:行者123 更新时间:2023-12-02 00:08:06 25 4
gpt4 key购买 nike

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

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

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

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();
}

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

Exception in thread "main" java.util.NoSuchElementException: No line found at java.base/java.util.Scanner.nextLine(Scanner.java:1651) at Mathiverse.main(Mathiverse.java:53)

最佳答案

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

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

关于java - 如何修复 "NoSuchElementException"被抛出的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58143034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com