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

如何修改Java代码:仅重新输入错误的除数y,而非全部输入参数?

优化Java程序的输入验证逻辑:仅重新输入错误的除数y

你的核心需求是:当数组索引x输入合法后,无论除数y出现0或者非数字的错误,只要求重新输入y,而不重新输入x。原代码的问题在于,y输入非数字时触发的InputMismatchException会被外层catch捕获,导致整个流程重启,需要重新输入x。下面是修改后的代码:

import java.util.Scanner;

public class Try {

    static int[] T = {17, 12, 15, 38, 29, 157, 89, -22, 0, 5};

    static int div(int index, int divider) {
        return T[index] / divider;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        // 先获取合法的数组索引x,直到输入正确
        int x = -1;
        while (true) {
            try {
                System.out.println("index : ");
                x = sc.nextInt();
                if (x < 0 || x >= T.length) {
                    System.out.println("Enter a number between 0 and " + (T.length - 1) + "\n");
                    continue;
                }
                break; // x合法,跳出循环
            } catch (java.util.InputMismatchException e) {
                System.out.println("Enter a number\n");
                sc.nextLine(); // 消费无效输入
            }
        }

        // x已合法,现在只循环处理y的输入,直到正确
        int y = 0;
        while (true) {
            try {
                System.out.println("divider: ");
                y = sc.nextInt();
                if (y == 0) {
                    System.out.println("Enter a divider different than Zero\n");
                    continue;
                }
                break; // y合法,跳出循环
            } catch (java.util.InputMismatchException e) {
                System.out.println("Enter a number\n");
                sc.nextLine(); // 消费无效输入
            }
        }

        // 执行计算并输出结果
        System.out.println("\n result: " + div(x, y));
        sc.close();
    }
}

关键改动说明

  • 拆分输入流程:把x和y的输入验证拆成两个独立的循环,确保x一旦输入合法,就不会再要求重新输入
  • 内聚异常处理:将y输入阶段的异常(非数字输入)在内部循环处理,避免异常扩散到外层导致流程重启
  • 移除冗余捕获:原代码中的ArithmeticException捕获可以去掉,因为已经在y输入阶段拦截了y=0的情况,div方法不会触发除零异常
  • 统一错误提示:对x和y的非数字输入、范围错误都给出明确提示,同时消费无效输入避免死循环

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 22:30:16