java中try catch语句块 总是循环输出 哪里错了

2025-05-22 08:38:07
推荐回答(1个)
回答(1):

nextInt方法,在发生异常时,不会接受用户再次输入的数据,而是徘徊在异常区域

使用nextLine即可

while(true){
    System.out.println("请输入1个整数: ");
    try{
        id = Integer.parseInt(input.nextLine().trim());
    }catch(NumberFormatException nfe){
        System.out.print("输入错误,");
        continue;
    }
}