捕获语句会重复执行

huangapple go评论123阅读模式
英文:

The catch statement repeatedly executes

问题

  1. 我正在尝试实现一个重新尝试捕获块

Scanner sc = new Scanner(System.in);

while (true){
try {
t = sc.nextInt();
break;
} catch (Exception e) {
System.out.println("请输入一个不带任何符号的整数!");
}
}

  1. 但问题在于,一旦控制流程到达并进入catch块,它就会再次进入catch块,并且在此之前永远不会尝试执行try块。
英文:

I am trying to implement a (re)try-catch block.

  1. Scanner sc = new Scanner(System.in);
  2. while (true){
  3. try {
  4. t = sc.nextInt();
  5. break;
  6. } catch (Exception e) {
  7. System.out.println("Please enter a whole number without any symbol(s)!");
  8. }
  9. }

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

这是我是如何解决的...

  1. /*java.util.*/Scanner sc = new /*java.util.*/Scanner(System.in);
  2. while(true)
  3. {
  4. if(sc.hasNextInt()){ t=sc.nextInt(); break;}
  5. System.out.println("请输入一个整数(介于-2,147,483,649和2,147,483,648之间),不要带任何符号!");
  6. sc.nextLine(); // hasNextInt()仅扫描缓冲区中的当前行
  7. }
英文:

Here's how I solved it...

  1. /*java.util.*/Scanner sc = new /*java.util.*/Scanner(System.in);
  2. while(true)
  3. {
  4. if(sc.hasNextInt()){ t=sc.nextInt(); break;}
  5. System.out.println("Please enter a whole number integer (between -2,147,483,649 and 2,147,483,648) without any symbol(s)!");
  6. sc.nextLine(); // hasNextInt() only scans the current line in the buffer
  7. }

huangapple
  • 本文由 发表于 2020年4月4日 19:55:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/61027688.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定