我是初学者,最近编译了一段书上的代码 发现运行结果和书上给出的不一样,所以想请教一下。先给出书上的范例代码,也就是我编译/执行的那段代码://Stdinput.java
import java.io.IOException;
public class Stdinput
{
public static void main(String[] agrs) throws IOException
{
System.out.println("intput:");
byte b[] = new byte[512];
int count = System.in.read(b);
System.out.println("output");
for(int i=0;i<count;i++)
{
System.out.print(b[i] + " ");
}
System.out.println();
for(int i=0;i<count;i++)
{
System.out.print((byte)b[i] + " ");//这样能输出字符?我把强制类型 byte 改成 char 后才正确输出了字符
}
System.out.println();
System.out.println("count=" + count);
}
}书上给出的运行结果:input:
abcd -------这里为自己从键盘输入
output
97 98 99 100 13 10 --------此处书上解释为"Enter键占用两个字节:13 10 所以保存在缓冲区 b[] 的元素个数为6个"
a b c d
count=6我编译后运行的结果:intput:
abcd
output
97 98 99 100 10
97 98 99 100 10 --------我把强制类型 byte 改成 char 后才正确输出了字符
count=5我想求教为什么会有以上的不同?是书上出错了还是因为我使用的操作系统的原因?望高手赐教!
import java.io.IOException;
public class Stdinput
{
public static void main(String[] agrs) throws IOException
{
System.out.println("intput:");
byte b[] = new byte[512];
int count = System.in.read(b);
System.out.println("output");
for(int i=0;i<count;i++)
{
System.out.print(b[i] + " ");
}
System.out.println();
for(int i=0;i<count;i++)
{
System.out.print((byte)b[i] + " ");//这样能输出字符?我把强制类型 byte 改成 char 后才正确输出了字符
}
System.out.println();
System.out.println("count=" + count);
}
}书上给出的运行结果:input:
abcd -------这里为自己从键盘输入
output
97 98 99 100 13 10 --------此处书上解释为"Enter键占用两个字节:13 10 所以保存在缓冲区 b[] 的元素个数为6个"
a b c d
count=6我编译后运行的结果:intput:
abcd
output
97 98 99 100 10
97 98 99 100 10 --------我把强制类型 byte 改成 char 后才正确输出了字符
count=5我想求教为什么会有以上的不同?是书上出错了还是因为我使用的操作系统的原因?望高手赐教!
97 98 99 100 10 --------我把强制类型 byte 改成 char 后才正确输出了字符在Linux系统的回车键是ASCII码应该是13,楼主你是不是写错啦?
windows的enter包括回车和换行两个字符,也就是\r\n
linux的enter只有换行字符,即\n
这点书上如果是针对windows可以说是正确的转成char才会输出字符,否则输出编码(因为是byte型),这点书上有误