为何用break无法跳出while循环?

windrain_p 2015-01-02 03:17:31

package com.wuziqi;
import java.io.*;

public class FileInput {
public static final int LENGTH = 100;
private static int readLine(byte line[]) throws IOException{
int i = 0;
int b = 0;
while(i<(LENGTH-1)&&(b=System.in.read())!='\n'){
line[i++]=(byte)b;
}//end while
return i;
}


public static void main(String[] args) {
// TODO Auto-generated method stub
byte [] name = new byte[LENGTH];
byte [] phone = new byte [LENGTH];
int countName=-1;
int countNumber=-1;
boolean isExit = false;
FileWriter out;
String n = "";
String p = "";

try{
out = new FileWriter("notes");
while(!isExit){
System.out.println("Please enter the name:");
countName=readLine(name);
n = new String(name, 0, countName);
if("exit".equalsIgnoreCase(n)){

break;
}
System.out.println("Please enter the phone number:");
countNumber=readLine(phone);
p = new String(phone, 0, countNumber);
out.write(n);
out.write(':');
out.write(p);
out.write('\n');
out.flush();
}//end while

out.close();
}//end try
catch(FileNotFoundException e){
System.err.println(e);
}
catch(IOException e){
System.err.println(e);
}
}


}


为何输入 exit 后循环依然继续??求各位帮帮我这个新手。。。。
...全文
1306 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
windrain_p 2015-01-02
  • 打赏
  • 举报
回复
是哦~~但是第一个while语句不是已经排除了换行符吗? while(i<(LENGTH-1)&&(b=System.in.read())!='\n'){ line[i++]=(byte)b; }
Leonhe2022 2015-01-02
  • 打赏
  • 举报
回复
楼主, 你有没有把if("exit".equalsIgnoreCase(n)){ 之前的n值打印出来? 它包含换行符的哦,equalsIgnoreCase返回会是false的,所以就不会执行break了。 需要加个trim:

if ("exit".equalsIgnoreCase(n.trim())) {

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧