我正在尝试实现一个(重新)try-catch块。
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块,并且在此之前从未尝试执行try块。
发布于 2020-04-04 20:10:43
这就是我是如何解决这个问题的。
/*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
}https://stackoverflow.com/questions/61027688
复制相似问题