捕获语句会重复执行

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

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
}

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:

确定