上面的一些回答正确地说你写的是一个无限循环。但我想澄清为什么这是一个无限循环。您使用的 for 循环与您可能想到的其他形式不同:
String[] stringArray = { "1", "2", "3" };
for (String s : stringArray) {
System.out.println(s);
}
在这种情况下,变量 s 会在每次迭代时使用集合或数组中的下一个值进行初始化。但是这种形式的 for 循环适用于集合和数组,不能与 Scanner 类等迭代器一起使用。
您使用的 for 循环形式的不同之处在于初始化子句(您有String s = in.next())在第一次通过循环时被调用ONLY。 s 是第一次设置的,然后就再也没有改变过。
你可以这样重写:
int i = 0;
for (String s = in.next(); !s.equals("end"); s = in.next()) {
System.out.println("The value of i is: " + i++ + " and you entered " + s);
}
但这里的另一个坏事是没有空值或结束检查。可以想象,如果您不太可能在找到等于“end”的字符串之前用完字符串。如果发生这种情况,那么 for 测试子句(中间那个)会在尝试调用 equals() 时给你一个 NullPointerException > 方法。这绝对是不好的做法。我可能会这样重写:
int i = 0;
while (in.hasNext()) {
String s = in.next();
if (s.equals("end")) {
break;
}
System.out.println("The value of i is: " + i++ + " and you entered " + s);
}
如果你真的想要一个 for 循环而不是 while,最好这样做:
int i = 0;
for (Scanner in = new Scanner(System.in); in.hasNext();) {
String s = in.next();
if (s.equals("end")) {
break;
}
System.out.println("The value of i is: " + i++ + " and you entered " + s);
}
根据测试子句中的字符串保留测试的最后一个变体如下所示:
int i = 0;
String s = "";
for (Scanner in = new Scanner(System.in);
in.hasNext() && !s.equals("end");
s = in.next()) {
System.out.println("The value of i is: " + i++ + " and you entered " + s);
}
您还可以在s.equals("end") 之前添加一个空检查以确保安全。