gpt4 book ai didi

java - 简单java程序出错

转载 作者:行者123 更新时间:2023-11-30 06:18:24 24 4
gpt4 key购买 nike

我正在自学 java,在使用类编写代码时遇到了这个错误

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at StateCalculator.getOperand(StateCalculator.java:29)
at StateCalculator.main(StateCalculator.java:77)

下面是我的代码:

import java.util.Scanner;


public class StateCalculator {
private double currentValue = 0;

//Initialize to 0
public StateCalculator() {
}

public static int displayMenu() {
Scanner keyboard = new Scanner(System.in);
int menuChoice = 0;

do {
System.out.print("Menu\n 1. Add\n 2. Subtract\n 3. Multiply\n 4. Divide\n 5.Clear\n 6. Quit\n What would you like to do?: ");
menuChoice = keyboard.nextInt();
} while(menuChoice < 1 || menuChoice > 6);

keyboard.close();
return menuChoice;
}

public static double getOperand(String prompt) {
Scanner input = new Scanner(System.in);
double operand = 0;

System.out.print(prompt);
operand = input.nextDouble();

input.close();
return operand;
}

public double getCurrentValue() {
return currentValue;
}

public void add(double operand) {
currentValue += operand;
}

public void subtract(double operand) {
currentValue -= operand;
}

public void multiply(double operand) {
currentValue *= operand;
}

public void divide(double operand) {
if(operand == 0) {
currentValue = Double.NaN;
}
else {
currentValue /= operand;
}
}

public void clear() {
currentValue = 0;
}


public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
StateCalculator calculator = new StateCalculator();
int option;
double operand;

do{
System.out.println("The current value is " + calculator.currentValue);
option = StateCalculator.displayMenu();

switch(option) {
case 1:
operand = getOperand("What is the second number?: ");
calculator.add(operand);
break;
case 2:
operand = getOperand("What is the second number?: ");
calculator.subtract(operand);
break;
case 3:
operand = getOperand("What is the second number?: ");
calculator.multiply(operand);
break;
case 4:
operand = getOperand("What is the second number?: ");
calculator.divide(operand);
break;
case 5:
calculator.clear();
break;
}

}while(option != 6);

keyboard.close();
}

}

我尝试在 eclipse 中运行调试功能,当我尝试设置 operand = input.nextDouble 时发现问题出现在我的 getOperand 方法的第 29 行。但是,我不明白为什么这会成为一个问题。

最佳答案

关闭 keyboard(您定义的)时不要调用 keyboard.close();

Scanner keyboard = new Scanner(System.in);

它关闭 System.in,然后您的其他方法将无法工作(因为控制台不会重新打开)。您可以在 System.in 上有多个扫描器(只要您不关闭它们),或者传递一个(或者,但请不要使用全局扫描器)。

根据 javadoc ,

When a Scanner is closed, it will close its input source if the source implements the Closeable interface.

关于java - 简单java程序出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24659149/

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