本人自学java 哪位达人能帮我看下这个代码为什么一个有结果而一个没有结果啊,主要就是break和continue
      byte[]arr=new byte[1024];
              while(true){   
               int ch=System.in.read();
                 int pos=0;
                
               if (ch=='\r') {
                 
                  continue;
}
                 if (ch=='\n') {
 String s=new String(arr,0,pos);
 if (s.equals("over")) {
break;
}
 System.out.println(s.toUpperCase());

}else 
arr[pos++]=(byte)ch;

               //////////////////////////////////////////////////
      StringBuilder builder=new StringBuilder();
           while (true) {
   int ch=System.in.read();
       if (ch=='\r') {
        System.out.println("123");
continue;
}
       if (ch=='\n') {
  String s=builder.toString();
  if (s.equals("over")) {
 break;
}
  System.out.println(s.toUpperCase());
    builder=builder.delete(0, builder.length());
}
       else 
        builder.append((char)ch);
}
请问这2个代码只是一个用了stringbulider一个是直接new了一个string为什么会结果不同啊 谢谢!!

解决方案 »

  1.   

    楼主第一段程序没贴完整,第二段程序我这里运行没啥问题。我猜测是第一段程序中if (s.equals("over")) {break;} 后面,没有把pos清0吧,这样造成换行后字符仍然在arr数组中不断累加。
      

  2.   

    我按你这个把pos=0了
       public static void readByinArry( )throws Exception{
                   byte[]arr=new byte[1024];
                  while(true){   
                   int ch=System.in.read();
                     int pos=0;
                    
                   if (ch=='\r') {
                     
                      continue;
    }
                     if (ch=='\n') {
     String s=new String(arr,0,pos);
     if (s.equals("over")) {
    break;
    }
     pos=0;
     System.out.println(s.toUpperCase());

    }else 
    arr[pos++]=(byte)ch;

                     }
                  
         } 
     但是还是运行的时候什么都没啊  没看出哪儿不对 
      

  3.   

    哦,是的,int pos=0,这个必须定义在循环外面,也就是:byte[]arr=new byte[1024];
    int pos=0;
    while(true){