2012-08-26 72 views
0

所以,我使用nextInt()從命令行中獲取用戶的整數輸入。但是,我的問題是,當用戶沒有輸入整數時,即只按下輸入而不輸入任何內容,nextInt()不會終止,而是繼續提示用戶,直到用戶輸入一個整數。是否有可能首先將「無輸入」作爲輸入,然後返回一條錯誤消息,指出沒有輸入整數? 在此先感謝!整數輸入使用nextInt()

+0

可能重複(http://stackoverflow.com/questions/5689325/blank-input-from-scanner-java) – assylias

+0

其中是碼? – Nishant

+0

如果添加[sscce](http://sscce.org)並指定使用java.util.Scanner,它將幫助所有人。 – gontard

回答

1
String line = null; 
    int val = 0; 
    try { 
     BufferedReader is = new BufferedReader(
     new InputStreamReader(System.in)); 
     line = is.readLine(); 
     val = Integer.parseInt(line); 
    } catch (NumberFormatException ex) { 
     System.err.println("Not a valid number: " + line); 
    } catch (IOException e) { 
     System.err.println("Unexpected IO ERROR: " + e); 
    } 
    System.out.println("I read this number: " + val); 
0

我假設您使用的是Scanner。如果是這樣,那麼你會想指定你會使用哪個delimiter。這樣的事情:

Scanner scanner = new Scanner(System.in); 
scanner.useDelimiter(System.getProperty("line.separator")); 
while (scanner.hasNextInt()){ 
    int i = sc.nextInt(); 
    /** your code **/ 
} 
0

你可以做一個嘗試/趕上。

String input = .... 
try { 
    int x = Integer.parseInt(input); 
    System.out.println(x); 
} 
catch(NumberFormatException nFE) { 
    System.out.println("Not an Integer"); 
} 
0

而不是整數嘗試把輸入作爲字符串。如果字符串爲空,那麼你提到的錯誤應該被提出,否則將字符串轉換爲整數。我不知道你的程序流是什麼,所以它的一個總體思路是,根據輸入需要解析字符串。在使用這個方法之前,你應該確保除了整數以外都沒有給出輸入。

0

嘗試的[空白輸入從掃描儀 - 的java]本

int number; 
boolean is_valid; 

    do { 
     try { 
      System.out.print("Enter Number :"); 
      Scanner kbd = new Scanner(System.in); 
      number = kbd.nextInt(); 
      is_valid = true; 
     } catch (Exception e) { 
      System.out.println("Invalid Integer "); 
      is_valid = false; 
     } 
    } while (!is_valid);