帮忙解释一下这个JAVA的回声程序,谢谢了!

class Echo1
{
Echo1(InputStream in) throws Exception
{
int b;
while ((b = in.read()) != -1)
{
System.out.print((char) b);
}
in.close();
}

public static void main(String[] args) throws Exception
{
new Echo1(System.in);
}
}

如果我不用构造方法,那这个程序应该怎么改呢?
看不懂键盘的数据究竟存在哪里了?从键盘上写不是用到写操作吗?不是应该用到OutputStream,为什么这个程序没有?

你理解错误了,键盘输入数据是读操作而不是写操作。
System.in返回的是标准的输入流,就是用来接收键盘输入的数据的。你说的OutputStream是输出流,而且是一个经过封装了的输出流,标准输出流是System.out。

至于如果不用构造方法,那可以另外写个方法来传递输入流对象嘛追问

如果只在主方法中完成,怎么办呢?

追答

public class Echo1
{
public static void main(String[] args) throws Exception
{
InputStream in = System.in;
int b;
while ((b = in.read()) != -1)
{
System.out.print((char) b);
}
in.close();
}
}

温馨提示:答案为网友推荐,仅供参考
相似回答