为什么我在输入 $ 后不退出 while 循环
why am I not exiting the while loop after I enter a $
当我输入 $ 时,我希望 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;
}
}
将您的代码更改为:
String oneLine = "";
while ( !oneLine.equals ("$") && oneLine != null){
oneLine = indata.readLine();
System.out.println(oneLine);
}
您正在将 BufferedReader 对象与 String 进行比较。我相信您想与当前行进行比较。同样如评论中所述 - 您需要将 oneLine
初始化为非空值,以避免在您第一次进入 while 循环时出现 NullPointerException
。
当我输入 $ 时,我希望 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;
}
}
将您的代码更改为:
String oneLine = "";
while ( !oneLine.equals ("$") && oneLine != null){
oneLine = indata.readLine();
System.out.println(oneLine);
}
您正在将 BufferedReader 对象与 String 进行比较。我相信您想与当前行进行比较。同样如评论中所述 - 您需要将 oneLine
初始化为非空值,以避免在您第一次进入 while 循环时出现 NullPointerException
。