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

Java多输入同try/catch捕获异常后跳回首个输入的解决方法

问题修复方案

不需要为每个输入单独编写重复的try/catch块,你可以抽取一个通用的数值读取方法,单次只处理一个数值的输入校验,出错时仅要求用户重新输入当前项,不会回退到已经完成的输入步骤。

问题根源

你现有代码的逻辑是将三个输入步骤全部放在同一个try块和循环中,只要任意一步输入触发异常,整个循环就会重启,已经输入成功的数值也会被重置,需要重新输入。

优化后代码

import java.util.Scanner;
import java.util.InputMismatchException;

public class GrabbingSmallestValueEntered {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        // 调用三次通用读取方法,分别获取三个数值
        double a = getValidNumber(input, "Input the first number: ");
        double b = getValidNumber(input, "Input the second number: ");
        double c = getValidNumber(input, "Input the third number: ");
        
        System.out.println("The smallest value is " + smallest(a, b, c) + "\n");
    }

    // 通用的合法数值读取方法
    private static double getValidNumber(Scanner input, String prompt) {
        while (true) {
            System.out.println(prompt);
            try {
                return input.nextDouble();
            } catch (InputMismatchException ie) {
                System.out.println("Only numbers allowed to be entered. No letters or words!");
                input.nextLine(); // 清空输入缓冲区的非法内容
            }
        }
    }

    public static double smallest(double a, double b, double c) {
        return Math.min(Math.min(a, b), c);
    }
}

优化优势

  • 没有重复的try/catch代码,后续如果要增加输入的数值数量,只需要多调用一次getValidNumber方法即可
  • 输入出错时仅重输当前错误项,不会让用户重复输入已经提交的正确内容
  • 逻辑拆分更清晰,输入校验和业务计算完全分离

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:15:03