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

Java中使用try-catch捕获异常后无法实现重试功能的问题

解决输入异常后无法重试的问题

嘿,我明白你遇到的问题了!你现在的代码里,try-catch只执行了一次——当用户输入无效内容触发InputMismatchException后,程序会执行catch块里的提示,但之后就直接跳出try-catch继续往下走了,自然没有重试的机会。另外还有个隐藏坑:当nextInt()抛出异常时,用户输入的无效字符还留在Scanner的输入缓冲区里,就算你加了循环,下次读取还是会直接拿到这些无效内容,再次触发异常。

我给你调整一下代码,解决这两个问题:

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

public class F_to_Celsius {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Bonjoir lol \n Convertire de Celsius à Fahrenheit tape 1 \n Convertire de Fahrenheit à Celsius tape 2 ");
        
        int choix = -1; // 初始化一个默认值
        boolean isValidInput = false;
        
        // 用循环包裹输入逻辑,直到用户输入有效内容
        while (!isValidInput) {
            try {
                choix = sc.nextInt();
                // 额外判断输入的数字是否在可选范围内
                if (choix == 1 || choix == 2) {
                    isValidInput = true;
                } else {
                    System.out.println("Veuillez entrer 1 ou 2 !");
                }
            } catch (InputMismatchException e) {
                System.out.println("Entrée invalide ! Veuillez entrer un nombre entier.");
                // 清空输入缓冲区里的无效内容,否则下次读取会重复触发异常
                sc.nextLine();
            }
        }
        
        // 这里可以继续处理用户的选择
        if (choix == 1) {
            System.out.println("Conversion Celsius -> Fahrenheit");
            // 后续逻辑...
        } else {
            System.out.println("Conversion Fahrenheit -> Celsius");
            // 后续逻辑...
        }
        
        sc.close();
    }
}

关键修正点:

  • 循环包裹输入逻辑:用while循环持续尝试,直到用户输入有效内容(isValidInput变为true),这样就能提供重试机会了。
  • 清空输入缓冲区:在catch块里调用sc.nextLine(),把用户输入的无效字符(比如字母、符号)从缓冲区里读走,避免下次nextInt()直接读取这些内容再次抛出异常。
  • 增加输入范围校验:额外判断用户输入的数字是不是1或2,就算输入了整数但不在可选范围内,也提示用户重新输入,体验更友好。

这样修改后,用户输入错误时就会一直收到提示,直到输入正确的1或2为止啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:04:02