如何在Java中停止无需使用break和exit的while循环

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

How to stop while loop without break and exit in java

问题

假设 while 循环无限运行,我们如何在不使用 break 或 System.exit() 的情况下停止循环?并且我们不能在循环中添加额外的条件,我们所做的任何操作都应该在循环外部完成。我们能实现吗?提前致谢。

英文:

Suppose while loop is running infinitely how can we stop the loop without using break or System.exit(). And also we cannot add extra condition in the loop whatever we do should be outside the loop.
Can we achieve that?
Thanks in advance

答案1

得分: 1

我不认为这是好的代码,但是为了演示一下(而且因为大多数面试问题的答案都很奇怪),你可以将整个循环包裹在 try-catch 中,并在循环内抛出一个 Exception

或者跳过 catch 块,在程序执行不需要继续的情况下抛出 RuntimeException

英文:

I would not consider it good code, but for the sake of it (and because most interview questions have weird answers anyway), you could wrap the whole loop in a try-catch and throw an Exception inside the loop.

Or skip the catch block and throw a RuntimeException if the program execution does not need to continue.

答案2

得分: 0

他们有一些方法:

1- 使用return;

2- 抛出异常并在下一步捕获它;

3- 我猜你有一些循环或者switch语句,你不想使用break,但是你可以给循环和break命名为inner和outer break。

英文:

they are some ways:

1- using return;

2- throw an exception and catch it next

3- I guess you have some loops or switches that you don't want to use break but you can name the loops and breaks to inner and outer break

答案3

得分: 0

你可以将循环放在一个类方法中,如果创建一个类实例并调用该方法来启动循环,你可以通过使用另一个类方法销毁进程或销毁类实例来停止循环。你还可以从循环外部调用执行输出工作的函数。

英文:

You can put your loop in a class method, and if you create a class instance and call the method to start the loop, you can stop the loop by destroying the process using another class method or by destroying the class instance. You can also call a function that does the output work from outside the loop.

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

发表评论

匿名网友

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

确定