标准的输入

标准的输入

问题的描述:

标准的输入

解决方案:

多数应用都会发生人机交互。人机交互经常通过控制台文本输入/输出来完成。

Java 2 SDK 用公有类java.lang.System支持控制台I/O。

System.out是一个PrintStream对象,它指向运行Java应用程序的终端窗口。

System.in是一个InputStream对象,它指向用户的键盘。

 

请看下例:

import java.io.*;

 

class TestKI // Keyboard Input

{

public static void main(String[] args) {

String s;

 

// 进行字符串的包装,就可以读取一行字符串

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

 

System.out.println("按 ctrl+c 键 或者输入exit 退出程序!");

 

try {

s = br.readLine();

// 如果按 ctrl+c 键,那么s==null,所以要先进行s!=null判断,不然

// 会出现空指针异常(调用s.equals("exit"))

while (s != null && !s.equals("exit")) {

System.out.println("Read: " + s);

s = br.readLine();

}

br.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

编译和运行的结果为:

posted @ 2012-08-16 17:49  深圳itjob  阅读(192)  评论(0)    收藏  举报