读取控制台输入
Java 的控制台输入由 System.in 完成:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
从控制台读取多字符输入
从 BufferedReader 对象读取一个字符要使用 read() 方法:
int read( ) throws IOException
每次调用 read() 方法,它从输入流读取一个字符并把该字符作为整数值(int)返回(所以要注意类型转换)
当流结束的时候返回 -1,该方法抛出 IOException
e.g.
1 2 3 4 5 6 7 8 9 | char c; // 使用 System.in 创建 BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("输入字符, 按下 'q' 键退出。"); // 读取字符 do { c = (char) br.read(); System.out.println(c); } while (c != 'q'); |
从控制台读取字符串
从标准输入读取一个字符串需要使用 BufferedReader 的 readLine() 方法:
String readLine( ) throws IOException;
e.g.
1 2 3 4 5 6 7 8 | // 使用 System.in 创建 BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; // 输入"end"退出 do { str = br.readLine(); System.out.println(str); } while (!str.equals("end")); |
Scanner输入
格式:Scanner scan = new Scanner(System.in); // 构造Scanner对象
Type t = scan.nextXxx();
next():只读取输入直到空格,并且光标指向本行
nextLine():读取输入到行尾的回车,将光标定位在下一行
以上均返回String类型
nextInt():只能读取整数,输入其它类型会报错,返回int。nextFloat(),nextDouble()同理
hasNextXxx();
对文件
判断文件是否有nextXxx()能接收的类型
e.g.
Scanner sc = new Scanner(new File("test.txt"));
System.out.println(sc.hasNext());
若test.txt为空(空格、tab、回车)则输出false,否则为true
对键盘输入
当输入为键盘时,该方法出现阻塞(block)。通常用于不停的读键盘输入,直到键入了非nextXxx()能接收的数据类型
e.g.
while (scan.hasNextDouble()) {
double x = scan.nextDouble();
}
上述示例在输入非数字时结束接收