这是我写的一个代码,通过命令行读入字符并输出,如过输入的是bye则退出程序,但下面的这个程序却无法实现退出
import java.io.*;public class Test{
public static void main(String[] args){ byte[] bt=new byte[100];
int ch=0;int pos=0;
String str;
while(true){
try{
ch=System.in.read();
if(ch=='\n'){
str=new String(bt,0,pos);
if(str.equals("bye"))
return;
System.out.println(str);
pos=0;
}
else{
bt[pos++]=(byte)ch;
}

}catch(IOException e){
System.out.println(e.getMessage());
}
}

}
}而如果我的if语句改成if(ch=='\n'||ch=='\r')则又能退出了,请高手指点迷津

解决方案 »

  1.   

    因为回车是\r\n,如果你只判断 if(ch == '\n'),那么你永远也得不到 bye ,当你输入 bye 回车之后,系统先读了\r,按你的程序,字符 ‘\r’就会被读到你的数组中,你判断的是bye\r ,而不是bye,自然就不会按你的要求退出程序了,
      

  2.   

    整行读嘛。BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));String line  = null;while( (line = reader.readLine())!=null && line.intern()!="bye"){
      if( line.intern()=="") continue;
      // ... 
    }