System.in 获取键盘输入
此处说明 两种使用System.in获取键盘输入的两种方法,分别是Scanner 和 InputStreamReader.
其中System.in 在System类中的定义如下:
package com.study; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class InputFromCommandLine { public static void main(String[] args) { input2(); } private static void input1() { try (Scanner sc = new Scanner(System.in)) { System.out.println("Input a num:"); int value = sc.nextInt(); System.out.println("Value Input:" + value); } catch (Exception e) { e.printStackTrace(); } } private static void input2() { try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { System.out.println("Input a num:"); String value = br.readLine(); System.out.println("Value Input:" + value); } catch (IOException e) { e.printStackTrace(); } } }
使用Scanner类时,需要注意,Scanner获取的是一个字符流。nextInt方法会不断读取字符,直到遇到非数字字符;nextLine会不断读取字符,直到遇到换行符。
package com.thinkjava.book; import java.util.Scanner; /** * Demonstrates a common problem using Scanner. * Scanner 获取的是字符流 */ public class ScannerBug { public static void main(String[] args) { String name; int age; Scanner in = new Scanner(System.in); System.out.print("What is your name? "); name = in.nextLine(); System.out.print("What is your age? "); age = in.nextInt(); System.out.printf("Hello %s, age %d\n", name, age); System.out.print("What is your age? "); age = in.nextInt(); in.nextLine(); //读取换行符,加上这行以避开bug System.out.print("What is your name? "); name = in.nextLine(); System.out.printf("Hello %s, age %d\n", name, age); } }
如下是一个通过System.in 方法获取键盘输入的方法,代码以及运行后的效果如下:
package com.thinkjava.book; import java.util.Scanner; /** * Converts centimeters to feet and inches. */ public class Convert { public static void main(String[] args) { double cm; int feet, inches, remainder; final double CM_PER_INCH = 2.54; final int IN_PER_FOOT = 12; Scanner in = new Scanner(System.in); // prompt the user and get the value System.out.print("Exactly how many cm? "); cm = in.nextDouble(); // convert and output the result inches = (int) (cm / CM_PER_INCH); feet = inches / IN_PER_FOOT; remainder = inches % IN_PER_FOOT; System.out.printf("%.2f cm = %d ft, %d in\n", cm, feet, remainder); } }
以上是手动输入一个参数193.04,之后由程序返回结果。
以下是通过命令行,将提供输入与实际输出的过程自动化。测试用例存储在纯文本文件中,并让Java以为这些输入来自键盘。
test.in.txt中存入测试用例,即参数193.04
在命令行中切换到Convert所在的目录,此处 test.in.txt 和Convert 类在同一个目录下:
在命令行中,<和>指的是重定向运算符。前者将test.in.txt 的内容重定向到 System.in,使得就像通过键盘输入了它们一样。后者将System.out的内容重定向到新文件test.out.txt,即test.out.txt包含程序的输出。
Author:LuffyStory
Origin:http://www.cnblogs.com/luffystory/