问题1
//PushbackInputStream类中unread()方法的应用
import java.io.*;
class PushbackIn{
public static void main(String args[]) throws IOException {
String s = "if (a == 4) a = 0;\n";
byte buf[] = s.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(buf);
PushbackInputStream f = new PushbackInputStream(in);
int c;
while((c = f.read()) != -1) {
switch(c) {
case '=':
if((c = f.read()) == '=')
System.out.print(".eq.");
else {
System.out.print("<-");
f.unread(c);
}
break;
default:
System.out.print((char) c);
break;
}
} }
}
输出为:if (a .eq. 4) a <- 0;
为什么'=='被替换成‘.eq. ’ 而 '=' 被替换成‘<-’呢?
if((c=f.read())=='=') System.out.print(".eq.")这句话的意思不是遇到等号时输出.eq.吗?
为什么从结果看是遇上==输出.eq.呢?
这里的f.unread(c);有什么作用,不用不行吗?
问题2//用System.in实现从键盘读取字节数组的操作
import java.io.*;
class SystemInDemo
{
public static void main(String args[])
throws IOException {
byte data[] = new byte[25]; //声明一个字节数组
System.out.println("Enter some characters.");
System.in.read(data);
System.out.print("You entered: ");
for(int i=0; i< data.length; i++)
System.out.print((char)data[i]); //依次输出数组data中的字符
}
}
如果把data[i]前面的(char)去掉则输出
//Enter some characters.
123rt
You entered: 4950511141161310000000000000000000
1的ASCII码为49,B的ASCII码为50 C的ASCII码为51
请问rt怎么会输出1141161310000000000000000000
System.out.println((char)data[i]); //依次输出数组data中的字符
输出一下就明白了。
1:49
2:50
3:51
r:114
t:116
剩下的13、10是输入回车时的符号,后面的一大串0,则是因为你定义了byte[25]的数组,没有读入数据的部分,都输出0。
if( ( c = f.read() ) == '=')把红色部分去掉
Pushes back a byte by copying it to the front of the pushback buffer. After this method returns, the next byte to be read will have the value (byte)b.
import java.io.*;class PushbackIn
{
public static void main(String args[]) throws IOException
{
String s = "if (a == 4) a = 0;\n";
byte buf[] = s.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(buf);
PushbackInputStream f = new PushbackInputStream(in);
int c;
while ((c = f.read()) != -1)
{
//总共是3个=
switch (c)
{
case '='://第一次:这里首先读到第一个 = 第三次:最后这里读到第三个=
if ((c = f.read()) == '=')//第二次:然后这里读到第二个=,所以==满足要求,正好输出.eq.
System.out.print(".eq.");
else//由于第三个=,满足这个分之,所以输出<-
{
System.out.print("<-");
f.unread(c);//把读指针往前移一位
}
break;
default:
System.out.print((char) c);
break;
}
}
System.out.println((char)61);
System.out.println('=');
System.out.println("==" == "=");
System.out.println("=" == "=");
}
}