gpt4 book ai didi

java - try catch Java 中的无限循环

转载 作者:行者123 更新时间:2023-12-01 18:59:09 24 4
gpt4 key购买 nike

我真的不知道这个问题......

如果数字不正确,该 block 会捕获异常,当我输入 -1 或 0 时,它会捕获异常并要求我再次输入数字...但如果我输入类似 asdasd 的内容,它将运行无限循环.

while (true){

try{

System.out.println("-Size of the array: ");
size = read.nextInt();

if(size<=0){

throw new Exception();

}else{

break;

}


}
catch(Exception e){

System.out.println("\n-Wrong input. Try again.\n");

}

}

最佳答案

处理此问题的最佳方法可能是更改它,以便读者获得下一行:

String input = read.nextLine();
if(input.length() == 0) { continue; }

try{
size = Integer.parseInt(input);
} catch(NumberFormatException e){ throw new Exception(); }

关于java - try catch Java 中的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12889649/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com