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
相关产品推荐
相关产品推荐

