之樾
2021-02-15 21:00
采纳率: 50%
浏览 29
已采纳

编写简易计算器时的报错

public class HomeworkDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String str = "";
        double i = 0;
        double j = 0;
        double result = 0;
        while (scanner.hasNextDouble()) {
            i = scanner.nextDouble();
            break;
        }
        while (scanner.hasNextLine()) {
            str = scanner.nextLine();
            switch (str) {
                case "+":
                    j = scanner.nextDouble();
                    result = add(i, j);
                    i = result;
                    System.out.println(result);
                    break;
                case "-":
                    j = scanner.nextDouble();
                    result = minus(i, j);
                    i = result;
                    System.out.println(result);
                    break;
                case "*":
                    j = scanner.nextDouble();
                    result = multiply(i, j);
                    i = result;
                    System.out.println(result);
                    break;
                case "/":
                    j = scanner.nextDouble();
                    result = divide(i, j);
                    i = result;
                    System.out.println(result);
                    break;
            }if (str.equals("quit")){
                System.out.println("退出计算机");
                break;
            }

            scanner.close();
        }
    }//加
    public static double add ( double a , double b){
        return a + b;
    }//减
    public static double minus ( double a , double b){
        return a - b;
    }//乘
    public static double multiply ( double a , double b){
        return a * b;
    }//除
    public static double divide ( double a , double b){
        return a / b;
    }


}

输出9-1就报错了,求教一下是哪里出了问题?

Exception in thread "main" java.lang.IllegalStateException: Scanner closed
    at java.util.Scanner.ensureOpen(Scanner.java:1070)
    at java.util.Scanner.findWithinHorizon(Scanner.java:1670)
    at java.util.Scanner.hasNextLine(Scanner.java:1500)
    at com.sean.base.method.HomeworkDemo.main(HomeworkDemo.java:25)

Process finished with exit code 1

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • 幻灰龙 2021-02-15 23:38
    已采纳

    >Exception in thread "main" java.lang.IllegalStateException: Scanner closed

    你在这个循环里就关闭了scanner, 循环体执行第二次时,sanner就已经不能用了。

    while (scanner.hasNextLine()) {
      ...
    
      scanner.close()
    
    }

    你觉的呢?

    已采纳该答案
    1 打赏 评论

相关推荐 更多相似问题