我正在尝试实现一个(重新)try-catch block 。
Scanner sc = new Scanner(System.in);
while (true){
try {
t = sc.nextInt();
break;
} catch (Exception e) {
System.out.println("Please enter a whole number without any symbol(s)!");
}
}
但这里的问题是,控件再次进入它到达的 catch block ,并且在此之前从未尝试执行 try block 。
最佳答案
这是我解决这个问题的方法...
/*java.util.*/Scanner sc = new /*java.util.*/Scanner(System.in);
while(true)
{
if(sc.hasNextInt()){ t=sc.nextInt(); break;}
System.out.println("Please enter a whole number integer (between -2,147,483,649 and 2,147,483,648) without any symbol(s)!");
sc.nextLine(); // hasNextInt() only scans the current line in the buffer
}
关于java - catch语句重复执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61027688/