在 Java 里 while 循环本身不会“报错”,报错通常是语法错误、逻辑错误、运行时异常导致的。下面按常见情况给你梳理一下,你可以对照看是哪一种。
while (i < 10 { // 少了右括号
i++;
}
✅ 解决:检查括号、分号是否完整
while (i < 10) { // i 没定义
i++;
}
✅ 解决:
int i = 0;
while (i < 10) {
i++;
}
int i = 0;
while (i < 10) {
System.out.println(i);
// 忘了 i++
}
✅ 解决:确保循环变量会变化
String s = null;
while (s.length() > 0) {
}
报错:
NullPointerException
✅ 解决:
while (s != null && s.length() > 0) {
}
int[] arr = {1,2,3};
int i = 0;
while (i <= arr.length) {
System.out.println(arr[i]);
i++;
}
报错:
ArrayIndexOutOfBoundsException
✅ 解决:
while (i < arr.length)
Scanner sc = new Scanner(System.in);
while (sc.nextInt() != -1) {
}
如果输入非整数会直接崩。
✅ 解决:
while (sc.hasNextInt()) {
int n = sc.nextInt();
if (n == -1) break;
}
System.out.println("i = " + i);
你可以把完整的 while 循环代码 + 报错信息贴出来,我可以直接帮你改 ✅
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。