英文:
The catch statement repeatedly executes
问题
我正在尝试实现一个(重新)尝试捕获块。
Scanner sc = new Scanner(System.in);
while (true){
try {
t = sc.nextInt();
break;
} catch (Exception e) {
System.out.println("请输入一个不带任何符号的整数!");
}
}
但问题在于,一旦控制流程到达并进入catch块,它就会再次进入catch块,并且在此之前永远不会尝试执行try块。
英文:
I am trying to implement a (re)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)!");
}
}
But the problem here is that the control again goes into the catch block ones it reaches there and never attempts to execute the try block before that.
答案1
得分: 1
这是我是如何解决的...
/*java.util.*/Scanner sc = new /*java.util.*/Scanner(System.in);
while(true)
{
if(sc.hasNextInt()){ t=sc.nextInt(); break;}
System.out.println("请输入一个整数(介于-2,147,483,649和2,147,483,648之间),不要带任何符号!");
sc.nextLine(); // hasNextInt()仅扫描缓冲区中的当前行
}
英文:
Here's how I solved it...
/*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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论