油漆计算程序Try/Catch循环异常问题排查请求
问题分析与修复方案
核心问题
你的代码存在三个关键问题,导致异常无法被正确处理:
- try-catch仅执行一次:输入非数字触发异常后,catch块处理完就退出流程,没有回到输入提示环节重新获取有效输入;
- 无效输入未清除:抛出
InputMismatchException后,Scanner缓冲区里的无效字符串仍存在,直接再次调用nextDouble()会持续触发异常; - catch块内错误调用
nextDouble():此时缓冲区还是无效输入,调用后必然再次抛异常,直接导致程序崩溃。
修复后的代码
import java.util.Scanner; import java.util.InputMismatchException; 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; // 获取有效墙高 do { try { System.out.println("Enter wall height (feet): "); wallHeight = scnr.nextDouble(); if (wallHeight <= 0) { System.out.println("Invalid: Height must be more than 0. Try again."); } } catch(InputMismatchException e) { System.out.println("Invalid: not a number. Try again."); scnr.nextLine(); // 清除缓冲区里的无效输入 wallHeight = 0.0; // 重置为无效值,让循环继续 } } while(wallHeight <= 0); // 获取有效墙宽 do { try { System.out.println("Enter wall width (feet): "); wallWidth = scnr.nextDouble(); if (wallWidth <= 0) { System.out.println("Invalid: Width must be more than 0. Try again."); } } catch(InputMismatchException e) { System.out.println("Invalid: not a number. Try again."); scnr.nextLine(); // 清除无效输入 wallWidth = 0.0; } } while(wallWidth <= 0); scnr.close(); // 计算并输出结果 wallArea = wallHeight * wallWidth; System.out.println("Wall area: " + wallArea + " square feet"); gallonsPaintNeeded = wallArea / squareFeetPerGallons; System.out.println("Paint needed: " + gallonsPaintNeeded + " gallons"); } }
关键修复点
- 将try-catch嵌入do-while循环内部,确保每次输入错误后都能回到输入提示流程;
- 捕获异常后调用
scnr.nextLine()清除Scanner缓冲区中的无效输入,避免后续读取操作重复触发异常; - 重置变量为无效值(如0.0),保证循环条件继续生效,直到用户输入符合要求的数据。
内容的提问来源于stack exchange,提问作者Sami Danielson
相关产品推荐
相关产品推荐

