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

带try-catch的Do-While循环异常退出及输入验证问题排查

问题分析与修复方案

核心错误点

  • 共用标志位导致第二个循环失效:两个验证循环共用decimal变量,第一个循环结束后decimal被设为true,第二个循环的while (!decimal)条件直接不成立,即使输入非法值也不会重复循环。
  • 无效输入清除方式错误:第一个循环的catch块中用scnr.nextDouble()清除输入,当输入非数字(如"thirty")时,该方法会再次抛出InputMismatchException,导致程序崩溃。
  • 异常处理逻辑漏洞:输入0时触发异常,但标志位未被重置为false,导致循环直接终止。

修复后的代码

import java.util.Scanner;

public class Paint1 {
    public static void main(String[] args) {  
        Scanner scnr = new Scanner(System.in);  
        double wallHeight = 0.0;  
        double wallWidth = 0.0;  
        double wallArea = 0.0;  
        double gallonsPaintNeeded = 0.0;  
        final double squareFeetPerGallons = 350.0;  

        // 验证墙高输入
        boolean heightValid = false;
        do {  
            try {  
                System.out.println("Enter wall height (feet): ");  
                wallHeight = scnr.nextDouble();  
                
                if (wallHeight <= 0) {  
                    throw new Exception("Invalid Input");  
                }  
                heightValid = true;  
            } catch (Exception e) {  
                System.out.println("Invalid Input");  
                scnr.nextLine(); // 清空整行无效输入
            }  
        } while (!heightValid);  

        // 验证墙宽输入
        boolean widthValid = false;
        do {  
            try {  
                System.out.println("Enter wall width (feet): ");  
                wallWidth = scnr.nextDouble();  

                if (wallWidth <= 0) {  
                    throw new Exception("Invalid Input");  
                }  
                widthValid = true;  
            } catch (Exception e) {  
                System.out.println("Invalid Input");  
                scnr.nextLine(); // 清空整行无效输入
            }  
        } while (!widthValid);  

        // 计算并输出结果
        wallArea = wallHeight * wallWidth;  
        System.out.println("Wall area: " + wallArea + " square feet");  

        gallonsPaintNeeded = wallArea / squareFeetPerGallons;  
        System.out.println("Paint needed: " + gallonsPaintNeeded + " gallons");  
    }  
}

关键修复说明

  1. 使用独立标志位:为墙高和墙宽分别设置heightValid、widthValid布尔变量,避免循环间的状态干扰。
  2. 正确清除无效输入:所有catch块中改用scnr.nextLine(),确保将用户输入的整行无效内容清空,避免后续读取操作触发异常。
  3. 确保标志位正确重置:只有当输入完全有效(是double且>0)时,才将对应标志位设为true,否则保持false,保证循环会重复执行直到输入合法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 19:16:14