java 控制台输入

  1 import java.io.BufferedReader;
  2 
  3 import java.io.Console;
  4 
  5 import java.io.InputStreamReader;
  6 
  7 import java.util.Scanner;
  8 
  9  
 10 
 11 /**
 12 
 13  * java 中控制台输入的几种实现方法
 14 
 15 * 
 16 
 17  * @author <a href="http://www.micmiu.com">Michael</a>
 18 
 19  * @time Create on 2013-10-21 下午4:55:30
 20 
 21  * @version 1.0
 22 
 23  */
 24 
 25 public class ConsoleInput {
 26 
 27  
 28 
 29 /**
 30 
 31  * @param args
 32 
 33  */
 34 
 35 public static void main(String[] args) throws Exception {
 36 
 37  
 38 
 39 // jdk1.5 之前的实现方式
 40 
 41 test1();
 42 
 43  
 44 
 45 // jdk5.0的Scanner实现方式
 46 
 47 // test2();
 48 
 49  
 50 
 51 // jdk6.0中Console实现方式 在IDE中获取console会失败
 52 
 53 // test3();
 54 
 55 }
 56 
 57  
 58 
 59 // jdk1.5 之前的实现方式
 60 
 61 public static void test1() throws Exception {
 62 
 63 String line = null;
 64 
 65 BufferedReader buffer = new BufferedReader(new InputStreamReader(
 66 
 67 System.in));
 68 
 69 System.out.print("please input :> ");
 70 
 71 while (!"exit".equals(line = buffer.readLine())) {
 72 
 73 System.out.println("input context = " + line);
 74 
 75 System.out.print("please input :> ");
 76 
 77 }
 78 
 79 System.out.println("The program will exit");
 80 
 81 }
 82 
 83  
 84 
 85 // jdk5.0 增加了java.util.Scanner类
 86 
 87 public static void test2() {
 88 
 89 Scanner scanner = new Scanner(System.in);
 90 
 91 String line = null;
 92 
 93 System.out.print("please input :> ");
 94 //scanner.next()   是根据空格来进行判断的 
 95 while (!"exit".equals(line = scanner.nextLine())) {
 96 
 97 System.out.println("input context = " + line);
 98 
 99 System.out.print("please input :> ");
100 
101 }
102 
103 System.out.println("The program will exit");
104 
105 }
106 
107  
108 
109 // jdk6.0 后增加java.io.Console(但在IDE中获取console会失败)
110 
111 public static void test3() {
112 
113 Console console = System.console();
114 
115 if (null == console) {
116 
117 System.out.println("Console is unavailable");
118 
119 System.exit(0);
120 
121 }
122 
123 String line = null;
124 
125 System.out.println(console);
126 
127 while (!"exit".equals(line = console
128 
129 .readLine("please input keyword :> "))) {
130 
131 System.out.println("input context = " + line);
132 
133 }
134 
135 System.out.println("The program will exit");
136 
137 }
138 
139  
140 
141 }

 

posted @ 2015-04-28 19:01  Maydow  阅读(131)  评论(0)    收藏  举报