java中从键盘输入的三种方法:
1import java.io.BufferedReader; 2import java.io.IOException; 3import java.io.InputStreamReader; 4import java.util.Scanner; 5 6public class Inout { 7 8 public static void main(String[] args) { 9 charTest(); //调用System.in方法 10 readTest(); //调用ReadTest方法 11 scannerTest();//调用ScannerTest方法 12 } 13 /** 14 * System.in和System.out方法 15 * 缺点一: 该方法能获取从键盘输入的字符,但只能针对一个字符的获取 16 * 缺点二: 获取的只是char类型的。如果想获得int,float等类型的输入,比较麻烦。 17 */ 18 public static void charTest(){ 19 try{ 20 System.out.print("Enter a Char:"); 21 char i = (char)System.in.read(); 22 System.out.println("Yout Enter Char is:" + i); 23 } 24 catch(IOException e){ 25 e.printStackTrace(); 26 } 27 28 } 29 /** 30 * InputStreamReader和BufferedReader方法 31 * 优点: 可以获取键盘输入的字符串 32 * 缺点: 如何要获取的是int,float等类型的仍然需要转换 33 */ 34 public static void readTest(){ 35 System.out.println("ReadTest, Please Enter Data:"); 36 InputStreamReader is = new InputStreamReader(System.in); //new构造InputStreamReader对象 37 BufferedReader br = new BufferedReader(is); //拿构造的方法传到BufferedReader中 38 try{ //该方法中有个IOExcepiton需要捕获 39 String name = br.readLine(); 40 System.out.println("ReadTest Output:" + name); 41 } 42 catch(IOException e){ 43 e.printStackTrace(); 44 } 45 46 } 47 /** 48 * Scanner类中的方法 49 * 优点一: 可以获取键盘输入的字符串 50 * 优点二: 有现成的获取int,float等类型数据,非常强大,也非常方便; 51 */ 52 public static void scannerTest(){ 53 Scanner sc = new Scanner(System.in); 54 System.out.println("ScannerTest, Please Enter Name:"); 55 String name = sc.nextLine(); //读取字符串型输入 56 System.out.println("ScannerTest, Please Enter Age:"); 57 int age = sc.nextInt(); //读取整型输入 58 System.out.println("ScannerTest, Please Enter Salary:"); 59 float salary = sc.nextFloat(); //读取float型输入 60 System.out.println("Your Information is as below:"); 61 System.out.println("Name:" + name +"\n" + "Age:" + age + "\n"+"Salary:" + salary); 62 } 63}
Console输入: (注:该种方法不能在eclipse中使用)
1import java.io.Console; 2import java.io.PrintWriter; 3 4public class TestConsole { 5 public static void main(String[] args) { 6 7 Console cons = System.console(); 8 if (cons != null) { 9 10 PrintWriter printWriter = cons.writer(); 11 printWriter.write("input:"); 12 cons.flush(); 13 String str1 = cons.readLine(); 14 cons.format("%s", str1); 15 } 16 } 17}
转载自:http://blog.csdn.net/u012249177/article/details/49586383