Java如何处理InputMismatchException?输入校验循环代码错误排查
问题分析
- 循环条件错误:
while(bool = false)是赋值操作,恒返回false,循环永远不会执行。同时你在进入循环前就直接调用scan.nextInt(),如果用户首次输入非整数,会直接抛出InputMismatchException,没有任何错误处理逻辑。 - 执行顺序颠倒:你先执行
scan.nextInt()读取输入,再判断输入类型,一旦输入不是整数,nextInt()直接抛出异常,后续的类型判断代码完全不会执行。 - 错误输入未消费:如果Scanner读取整数失败,输入指针不会自动后移,会一直卡在错误的输入内容上,必须主动调用
nextLine()清空缓存的错误输入,否则会进入死循环。 - 类型判断逻辑错误:
hasNextDouble()会匹配整数(整数也属于合法的double范围),同时hasNext()只要有输入就会返回true,二者的判断顺序和逻辑会导致错误提示不准确。
修正后代码
import java.util.Scanner; public class LoopPrac { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int num; boolean inputValid = false; while (!inputValid) { System.out.println("Enter an Integer: "); // 先判断输入是否为整数 if (scan.hasNextInt()) { num = scan.nextInt(); inputValid = true; // 消费剩余换行符 scan.nextLine(); System.out.println(num); } else { // 读取错误输入内容用于类型判断 String wrongInput = scan.nextLine(); try { // 尝试转换为浮点数判断输入类型 Double.parseDouble(wrongInput); System.out.println("Error: Index is Double not Integer."); } catch (NumberFormatException e) { System.out.println("Error: Index is String not Integer."); } } } scan.close(); } }
内容的提问来源于stack exchange,提问作者L. Jacob
相关产品推荐
相关产品推荐

