1. 程式人生 > >Java中從控制檯輸入資料的幾種常用方法

Java中從控制檯輸入資料的幾種常用方法

一、使用標準輸入串System.in

  //System.in.read()一次只讀入一個位元組資料,而我們通常要取得一個字串或一組數字
  //System.in.read()返回一個整數
  //必須初始化
  //int read = 0;
  char read = '0';
  System.out.println("輸入資料:");
  try {
   //read = System.in.read();
   read = (char) System.in.read();
  }catch(Exception e){
   e.printStackTrace();
  }
  System.out
.println("輸入資料:"+read);

二、使用Scanner取得一個字串或一組數字

  System.out.print("輸入");
  Scanner scan = new Scanner(System.in);
  String read = scan.nextLine();
  System.out.println("輸入資料:"+read); 

/*在新增一個Scanner物件時需要一個System.in物件,因為實際上還是System.in在取得使用者輸入。Scanner的next()方法用以取得使用者輸入的字串;nextInt()將取得的輸入字串轉換為整數型別;同樣,nextFloat()轉換成浮點型;nextBoolean()轉換成布林型。*/

三、使用BufferedReader取得含空格的輸入

//Scanner取得的輸入以space, tab, enter 鍵為結束符,
  //要想取得包含space在內的輸入,可以用java.io.BufferedReader類來實現
  //使用BufferedReader的readLine( )方法
  //必須要處理java.io.IOException異常
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in ));
  //java.io.InputStreamReader繼承了Reader類
  String read = null
; System.out.print("輸入資料:"); try { read = br.readLine(); } catch (IOException e) { e.printStackTrace(); } System.out.println("輸入資料:"+read);