HOWTO · Java

在 Java 中檢查輸入是否為整數

本文介紹瞭如何在 Java 中判斷一個輸入是否為整數。

問題指出,我們需要檢查 Java 語言中的輸入是否為整數。

使用 Java 中的 hasNextInt 方法檢查輸入是否為整數

System 是具有靜態方法和欄位的類。我們永遠不能例項化它的物件。in 物件是標準輸入流。該流已經開啟,可以提供輸入數了。

hasNextMethod 存在於 Scanner 類中,如果此掃描程式輸入中的下一個標記可以被評估為 int 值,則返回 true。如果關閉了掃描程式物件,則該方法將丟擲 IllegalStateException

package checkInputIsInt;

import java.util.Scanner;

public class CheckIntegerInput {
  public static void main(String[] args) {
    System.out.print("Enter the number: ");
    Scanner scanner = new Scanner(System.in);
    if (scanner.hasNextInt()) {
      System.out.println("The number is an integer");
    } else {
      System.out.println("The number is not an integer");
    }
  }
}

在第一行中,使用控制檯輸入從使用者那裡獲取輸入。由於輸入的文字是數字,因此該數字是要列印的整數。

Enter the number: 1
The number is an integer

由於輸入的文字不是數字,因此將列印 else 條件語句。

Enter the number: Hi
The number is not an integer

使用 try...catch 塊檢查數字是否為整數

在下面的程式碼塊中,我們使用 Scanner 類從控制檯獲取使用者輸入。Scanner 類具有 next 方法。如果沒有更多可用的令牌,則丟擲 NoSuchElementException,如果關閉此 Scanner,則丟擲 IllegalStateException

public class CheckIntegerInput {
  public static void main(String[] args) {
    System.out.print("Enter the number : ");
    Scanner scanner = new Scanner(System.in);
    try {
      Integer.parseInt(scanner.next());
      System.out.println("The number is an integer");
    } catch (NumberFormatException ex) {
      System.out.println("The number is not an integer ");
    }
  }

如果數字是整數,則上面的程式碼將在 try 塊中顯示該語句。如果該方法從其丟擲 Exception,則將執行 catch 塊中存在的語句;如果無法將字串轉換為數字型別之一,則將丟擲 NumberFormatException

上面程式碼的輸出類似於上面給出的第一個示例程式碼中的輸出。