Java中從控制檯輸入數據的幾種經常使用方法(轉轉)

 

原文博客地址:https://www.cnblogs.com/SzBlog/p/5404246.htmlhtml

 

 

1、使用標準輸入串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);java

2、使用Scanner取得一個字符串或一組數字
  System.out.print("輸入");
  Scanner scan = new Scanner(System.in);
  String read = scan.nextLine();
  System.out.println("輸入數據:"+read); spa

/*在新增一個Scanner對象時須要一個System.in對象,由於實際上仍是System.in在取得用戶輸入。Scanner的next()方法用以取得用戶輸入的字符串;nextInt()將取得的輸入字符串轉換爲整數類型;一樣,nextFloat()轉換成浮點型;nextBoolean()轉換成布爾型。*/htm

3、使用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); blog

相關文章
相關標籤/搜索