public static void main(String[] args) {
// TODO: Add your code here
byte [] buf=new byte[1024];
String strInfo=null;//对于在main方法中定义的对象必须进行显示的初始化
int pos=0;
int ch=0;
//System.out.println("please input sting:".indexOf('i',8));
System.out.println("please input string:".substring(6,8));
while(true)
{
try{ch=System.in.read();}
catch(Exception e){} //读取一个字节的内容
switch(ch)
{
case '\r':
break;
case '\n':
strInfo=new String(buf,0,pos);
if(strInfo.equals("bye"))
{
return;
}
else
{
System.out.println(strInfo);
pos=0;
break;
}
default:
buf[pos++]=(byte)ch;
}
}
   
}
大家看看我这个程序,我就是有一点弄不清楚,read()方法只能读取一个字节的内容,String(buf,0,pos)在程序中表面上没有与read()发生联系,为什么能形成一个字符串呢??

解决方案 »

  1.   

    default: 
    buf[pos++]=(byte)ch; 
    这里的ch就是read有关,而把ch放到了buf中,然后通过buf再生成字符串啊.
      

  2.   

    strInfo=new String(buf,0,pos); 这一句与read()的关系,还有pos ,  一开始pos=0,在ch=System.in.read()后 为什么pos会自动累加??
      

  3.   

    public static void main(String[] args) { 
        // TODO: Add your code here 
        byte [] buf=new byte[1024]; 
        String strInfo=null;//对于在main方法中定义的对象必须进行显示的初始化 
        int pos=0; 
        int ch=0; 
        //System.out.println("please input sting:".indexOf('i',8)); 
        System.out.println("please input string:".substring(6,8)); 
        while(true) 
        { 
            try{ch=System.in.read();} 
            catch(Exception e){} //读取一个字节的内容 
             switch(ch) 
            { 
                 case '\r': //如果输入的字符为'\r'不处理
                     break; 
                 case '\n': //如果输入的字符为'\n'换行符
                     strInfo=new String(buf,0,pos); //这时buf中可能已经有了内容,default以下那句负责填充buf的内容
                     if(strInfo.equals("bye")) //如果输入的字符串即buf中的内容为"bye"
                     { 
                        return;                //从main中返回,即退出程序
                     } 
                     else 
                     { 
                         System.out.println(strInfo); //输出buf中缓存的字符
                         pos=0; 
                         break; 
                     } 
                 default: //如果输入的字符既不是'\n'或者'\r'的情况下
                     buf[pos++]=(byte)ch; //buf储存输入的字符,并将pos自增1
             } 
         } 
     } 
    strInfo=new String(buf,0,pos); 这一句与read()的关系,还有pos ,  一开始pos=0,在ch=System.in.read()后 为什么pos会自动累加??看default后面那句语句...