class test
{
public static void main(String args[])throws Exception
{
System.out.println("please input a string");
int i=0;
byte[] buf=new byte[1024];
while(true)
{
int ch=System.in.read();
if(i>10) System.exit(0);
switch(ch)
{
case '\r':
break;
case '\n':
String s=new String (buf,0,i);
for(int j=0;i<s.length();j++)
System.out.println(Integer.toHexString((int)(s.charAt(j))));
break;
default:
buf[i++]=(byte)ch;
break;
}
}
}
}
为什么输入回车也不执行System.out.println(Integer.toHexString((int)(s.charAt(j))))?
{
public static void main(String args[])throws Exception
{
System.out.println("please input a string");
int i=0;
byte[] buf=new byte[1024];
while(true)
{
int ch=System.in.read();
if(i>10) System.exit(0);
switch(ch)
{
case '\r':
break;
case '\n':
String s=new String (buf,0,i);
for(int j=0;i<s.length();j++)
System.out.println(Integer.toHexString((int)(s.charAt(j))));
break;
default:
buf[i++]=(byte)ch;
break;
}
}
}
}
为什么输入回车也不执行System.out.println(Integer.toHexString((int)(s.charAt(j))))?
应该是j<s.length()。帮忙解释一下‘\r’,'\n'吧
\n换行
你输入:enter键,这两个都有吧。
你的错误不在这里,是因为for(int j=0;i<s.length();j++)这句写错了,第二个j写成了i,粗心的问题
class test
{
public static void main(String args[])throws Exception
{
System.out.println("please input a string");
int i=0;
byte[] buf=new byte[1024];
while(true)
{
int ch=System.in.read();
if(i>10) System.exit(0);
switch(ch)
{
case '\r':
break;
case '\n':
String s=new String (buf,0,i);
for(int j=0;j<s.length();j++) //因为这一行你把第二个j错写成了i,改成我这样
System.out.println(Integer.toHexString((int)(s.charAt(j))));
break;
default:
buf[i++]=(byte)ch;
break;
}
}
}
}
怎么还可以执行 case '\n'呢?应该是顺序执行啊,结束SWITCH
但你外面不是有个while(true)循环么?
\r进了一次循环,进入switch,结束switch
接下来\n又进如循环,进入switch,结束switch
如此循环往复,直到你输入的字符超过10个为止
不是这样的吧windows下是'\n\r'
linux下是'\n'
\n 新行windows 、http 使用 \r\n
*ix 使用 \n
mac 使用 \r
read是流读入啊
你输入回车(\r\n)有两个字符,就能支持while循环跑2次了,要是输入abc+回车,就能跑5次了
这跟给车加多少油就能跑多远一个道理。
{
public static void main(String args[]) throws Exception
{
System.out.println("please input a string");
int i = 0;
byte[] buf = new byte[1024];
while (true)
{
int ch = System.in.read();
if (i > 10)
System.exit(0);
switch (ch) {
case '\r':
System.out.println();
break;
case '\n':
String s = new String(buf, 0, i);
for (int j = 0; j < s.length(); j++)
// 因为这一行你把第二个j错写成了i,改成我这样
System.out
.println(Integer.toHexString((int) (s.charAt(j))));
break;
default:
buf[i++] = (byte) ch;
break;
}
}
}
}
如输入qw enter
*
q
w
直到你输入的字符超过10个为止
如alexandertech所说。 不要把简单想复杂了 enter 是\r\n
2.在Windows下回车表示“\r\n”,在Linux下表示“\n”
3.String s=new String (buf,0,i);有问题。不明白这句什么意思。换成String s=String.valueOf((char)ch);
返回a