2014-02-27 40 views
-3

我使用以下代碼段從java中的控制檯獲取10個輸入,並嘗試以*******12格式打印它們。在運行時,我輸入12,13,14,15作爲輸入,然後程序終止。現在有3個問題:在java中獲取來自控制檯的輸入

  1. 爲什麼這個代碼只有5個輸入,而不是10?
  2. 爲什麼這段代碼打印輸入14例如49,52,10?
  3. 解決方案是什麼?

代碼:

public static void main(String[] args) { 
    for (int i = 0 ; i <10 ;i++){ 
     try { 
      int j= System.in.read(); 
      System.out.println("**********"+j); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 

    } 
} 

輸出功率爲:

12 
**********49 
**********50 
**********10 13 
**********49 
**********51 
**********10 14 
**********49 
**********52 
**********10 15 
**********49 

BUILD SUCCESSFUL(總時間:14秒),

+0

是什麼'閱讀()'做什麼?你正在使用它,所以我會假設你已經查閱了它。 –

+0

你可能想閱讀這個http://stackoverflow.com/questions/15446689/what-is-the-use-of-system-in-read-in-java –

+0

「爲什麼這個代碼只有5個輸入,而不是10個? 」。因爲你輸入了10個字節,這是in.read()讀取的內容。 –

回答

7

49,52和10是用於按下的字符的ASCII字符代碼, 輸入

您可以繼續使用System.in.read(),並在每個字符到達時處理它。你會做類似如下:

  • 收集鍵入的字符
  • 找數字鍵入之後輸入
  • 轉換的數字的ASCII碼爲十進制數

這當然正是Scanner.nextInt()爲你做的。

+0

那麼解決方案是什麼? – zari

+0

按照其他答案的建議,您可以使用'Scanner'和'nextInt()'。 –

+0

表示無法修復in.read()? – zari

3

你想使用ScannernextInt()方法。試試這個:

public static void main(String[] args) { 
    Scanner s = new Scanner(System.in); 
    for (int i = 0; i < 10; i++) { 
     int j = s.nextInt(); 
     System.out.println("**********" + j); 
    } 
} 

注意read()InputStream類的方法。您通常不想直接訪問InputStream

+0

是的,我知道類Scaner是另一種解決方案。但是我需要一個使用System.out.read()的解決方案。那麼上面的代碼有什麼問題? – zari

+0

如果你的意思是'System.in.read()',那麼沒有理由。掃描儀是訪問「InputStream」的簡單而安全的方式。 – nrubin29

+0

含義用於繼承,因爲它是抽象類? – zari

1

如果當你寫一個字,然後按輸入要運行的IDE

String input = System.console().readLine(); 
1

這個之外,它轉換成3個字節:character_code + \ r + \ n。在你的情況下,它需要3次迭代我變量。

對於輸入的2個字符,它會翻譯爲:character_code + character_code + \ r + \ n。它需要我4次迭代。

順便說一句,我還有一個輸出相同的代碼:

 
12   
**********49 
**********50 
**********13 
**********10 
13   
**********49 
**********51 
**********13 
**********10 
14   
**********49 
**********52 
+0

謝謝。你也有幫助。 :) – zari

0

這也將有助於櫃面你想使用BufferedReader

public static void main(String[] args) throws NumberFormatException, IOException { 
    BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); 

    for(int i = 0; i<10; i++){ 
     int inp = Integer.parseInt(stdin.readLine()); 
     System.out.println("----------- "+inp); 
    }