一个java数组小程序的问题~~~~???急

来源:百度知道 编辑:UC知道 时间:2024/06/11 10:52:38
public class ReadLine
{
public static void main(String [] args)
{
byte buf[]=new byte[1024];
String strInfo=null;
int pos=0;
int ch=0;
System.out.println("please enter info, input bye for exit:");
while(true)
{
try
{
ch=System.in.read();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
switch(ch)
{
case '\r':
break;
case '\n':
strInfo= new String(buf,0,pos);
if(strInfo == "bye")
return ;
else
System.out.println(strInfo);
pos=0;
break;
default:
buf[pos++]=(byte)ch;
}
}
}
}
上面这个程序,能帮我说一下他的执行过程吗》》~??具体说两次循环就行,还有就是这个:strInfo= new String(buf,0,pos);到底是怎么执行的,从buf的第0个元素开始到buf的pos个元素的话那第一次循环时事0到0??那第二次是什么????不明白啊~~~~~~~~~~~~~~~

读入键盘输入的每个字节,
注意,如果不是换行字符,就累加到buf当中;
如果是换行,那就把buf当中的东西创建为String,显示出来,并复位,重新开始读键盘了。

关于从0到0,仅当你上来就敲一个回车,这时候创建一个空串而已。

关键是看懂switch语句。
在没敲回车和换行前都执行:buf[pos++]=(byte)ch;
把每一个从键盘读到每个byte缓存进buf这个字节数组。
注意这里pos++,对pos进行累加!