Java获得键盘输入的两种方法

 1 import java.io.BufferedReader;
 2 import java.io.IOException;
 3 import java.io.InputStreamReader;
 4 import java.util.Scanner;
 5 
 6 public class MainClass
 7 {
 8         public static void method1()
 9         {
10                 //使用Scanner
11                 Scanner scanner=new Scanner(System.in);
12                 System.out.print("Please input a number:");
13                 int num=scanner.nextInt();  //获取整数值
14                 System.out.println("The number you input is:"+num);
15                 System.out.println("----------------------------");
16                 System.out.print("Please input some character:");
17                 String str=scanner.next();  //获取字符串值
18                 System.out.println("The string you input is:"+str);
19                 
20         }
21         public static void method2()
22         {
23                 //使用BufferedReader
24                 try
25                 {
26                         BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
27                         System.out.print("Please input a number:");
28                         String str=reader.readLine();  //获取字符串
29                         System.out.println("The number you input is:"+str);
30                         
31                 } catch (IOException e)
32                 {
33                         e.printStackTrace();
34                 }
35         }
36 }

posted @ 2013-10-19 22:14  铅笔人生  阅读(1110)  评论(0编辑  收藏  举报