当我输入$时,我会期望退出while循环,但它会继续循环。谢谢你的帮助
import java.io.*;
import java.util.*;
public class test {
public static void main(String[] args) {
String oneLine = "";
try {
BufferedReader indata = new
BufferedReader(new InputStreamReader(System.in));
while (!oneLine.equals("$")) {
oneLine = indata.readLine();
System.out.println(oneLine);
}
}
catch (Exception e) {
System.out.println("Error --" + e.toString());
}
System.out.println("outside of while \n");
return;
}
}
答案 0 :(得分:0)
将您的代码更改为:
String oneLine = "";
while ( !oneLine.equals ("$") && oneLine != null){
oneLine = indata.readLine();
System.out.println(oneLine);
}
您正在将BufferedReader对象与String进行比较。我相信你想要与现有的线路进行比较。同样如评论中所述 - 您需要将oneLine
初始化为非空值,以便在您第一次进入while循环时避免NullPointerException
。