You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行方法后如何返回switch case菜单?Scanner异常问题求助

解决菜单循环返回与Scanner异常问题

嘿,我来帮你搞定这两个问题!咱们一步步拆解分析:

问题1:循环无法返回菜单(编译+逻辑双重问题)

你现在把selection变量定义在do代码块内部了,这就导致while(selection !=6)这个条件根本访问不到它——变量的作用域只限于do块里。这不仅会触发编译报错,也是循环没法正常工作的核心原因。

问题2:NoSuchElementException异常

这个异常大概率是因为你在sumOfIntegers()、factorialOfNumber()这些子方法里,也创建了独立的Scanner对象,并且在方法结束时调用了close()。一旦关闭任何一个关联到System.in的Scanner,整个标准输入流都会被关闭,主方法里的Scanner再尝试读取时就会抛出这个异常。


修复后的完整代码

import java.util.Scanner;

public class ArithmeticMenu {
    public static void main(String[] args) {
        String menu = ("Please choose one option from the following menu: \n"
                + "1. Calculate the sum of integers 1 to m\n"
                + "2. Calculate the factorial of a given number\n"
                + "3. Calculate the amount of odd integers in a given sequence\n"
                + "4. Display the leftmost digit of a given number\n"
                + "5. Calculate the greatest common divisor of two given integers\n"
                + "6. Quit\n");

        Scanner console = new Scanner(System.in);
        int selection; // 把变量移到循环外,扩大作用域
        do {
            System.out.println(menu);
            
            // 处理非法输入:避免用户输入非整数导致崩溃
            while (!console.hasNextInt()) {
                System.out.println("请输入有效的数字选项!");
                console.next(); // 吃掉无效输入,避免死循环
            }
            
            selection = console.nextInt();

            switch (selection) {
                case 1:
                    sumOfIntegers(console); // 传递主Scanner给子方法,复用输入流
                    break;
                case 2:
                    factorialOfNumber(console);
                    break;
                case 3:
                    calcOddIntegers(console);
                    break;
                case 4:
                    displayLeftDigit(console);
                    break;
                case 5:
                    greatestCommonDivisor(console);
                    break;
                case 6:
                    System.out.println("Bye");
                    break;
                default:
                    System.out.println("无效选项,请输入1-6之间的数字!");
            }
        } while (selection != 6);
        
        console.close(); // 仅在主方法最后关闭一次Scanner
    }

    // 子方法统一接收主Scanner参数,不再创建新的Scanner
    private static void sumOfIntegers(Scanner console) {
        System.out.println("请输入整数m:");
        int m = console.nextInt();
        int sum = 0;
        for (int i = 1; i <= m; i++) {
            sum += i;
        }
        System.out.println("1到" + m + "的和是:" + sum);
    }

    private static void factorialOfNumber(Scanner console) {
        System.out.println("请输入要计算阶乘的数字:");
        int num = console.nextInt();
        int factorial = 1;
        for (int i = 1; i <= num; i++) {
            factorial *= i;
        }
        System.out.println(num + "的阶乘是:" + factorial);
    }

    private static void calcOddIntegers(Scanner console) {
        System.out.println("请输入序列(输入-1结束):");
        int count = 0;
        int num;
        while ((num = console.nextInt()) != -1) {
            if (num % 2 != 0) {
                count++;
            }
        }
        System.out.println("序列中的奇数个数是:" + count);
    }

    private static void displayLeftDigit(Scanner console) {
        System.out.println("请输入一个数字:");
        int num = Math.abs(console.nextInt());
        while (num >= 10) {
            num /= 10;
        }
        System.out.println("最左边的数字是:" + num);
    }

    private static void greatestCommonDivisor(Scanner console) {
        System.out.println("请输入第一个整数:");
        int a = console.nextInt();
        System.out.println("请输入第二个整数:");
        int b = console.nextInt();
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        System.out.println("最大公约数是:" + Math.abs(a));
    }
}

关键修改点说明

  1. 变量作用域调整:把selection移到do-while循环外部,让while条件能正常读取到它,循环才能正确判断是否继续执行。
  2. Scanner复用:所有子方法都接收主方法创建的Scanner作为参数,不再单独创建新的Scanner,也不在子方法里调用close()——只在主方法最后统一关闭,避免输入流被提前终止。
  3. 非法输入防护:添加了while (!console.hasNextInt())的逻辑,防止用户输入非整数导致程序崩溃,提升了程序的健壮性。
  4. 无效选项提示:在switch里新增default分支,处理用户输入1-6以外的选项,给用户明确的反馈。

这样修改后,你的程序就能在执行完每个功能后自动回到菜单,也不会再出现Scanner相关的异常啦!

内容的提问来源于stack exchange,提问作者KodaNotABear

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 18:21:00