簡體   English   中英

使用nextInt()的整數輸入

[英]Integer inputs using nextInt()

因此,我使用nextInt()在命令行中從用戶獲取整數輸入。 但是,我的問題是; 當用戶不輸入整數時,即僅按Enter鍵而不輸入任何內容時,nextInt()不會終止,而是繼續提示用戶,直到用戶輸入整數為止。 是否可以將第一個“無輸入”作為輸入,然后返回一條錯誤消息,指出沒有輸入整數? 提前致謝!

 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);

我假設您正在使用Scanner 如果是這樣,那么您將要指定使用哪個delimiter 像這樣:

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

您可以嘗試/捕獲。

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

代替整數嘗試將輸入作為字符串。 如果字符串為空,則將引發您提到的錯誤,否則將字符串轉換為整數。 我不知道您的程序是什么流程,因此它是一個一般性的想法,根據輸入內容將需要對字符串進行解析。 同樣,在使用此方法之前,您應確保除整數外沒有其他輸入。

嘗試這個

 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM