您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,要终止一个无限循环,可以使用以下方法:
for (int i = 0; i < Integer.MAX_VALUE; i++) {
if (i == 10) {
break; // 当i等于10时,跳出循环
}
System.out.println(i);
}
boolean stopLoop = false;
for (int i = 0; i < Integer.MAX_VALUE; i++) {
if (stopLoop) {
break; // 当stopLoop为true时,跳出循环
}
System.out.println(i);
if (i == 10) {
stopLoop = true; // 当i等于10时,设置标志变量为true,终止循环
}
}
class TerminateLoopException extends RuntimeException {
public TerminateLoopException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
try {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
if (i == 10) {
throw new TerminateLoopException("Terminate loop at i = 10");
}
System.out.println(i);
}
} catch (TerminateLoopException e) {
System.out.println(e.getMessage()); // 当抛出异常时,捕获并处理异常,终止循环
}
}
}
请注意,这些方法仅适用于可以控制的循环。如果循环是由外部因素触发的,例如用户输入或系统事件,那么需要根据具体情况采取不同的策略来终止循环。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。