我試圖驗證用戶輸入的只有1,2或3.到目前爲止,我已經使用sc.hasNextInt()來驗證整數,但不是那些特定的。有人可以幫忙嗎?我的代碼如下。驗證java中某些值的整數
System.out.print("Enter Department Number: ");
while (!sc.hasNextInt())
{
System.out.println("Invalid entry. Please enter 1, 2, or 3 for the
department number.");
System.out.print("Enter Department Number: ");
sc.next();
}
int department = (sc.nextInt());
如果我輸入一個非數字值,並不斷地循環,這將引發我的系統錯誤代碼如果我輸入一個數字。 –
如果您想輸入String並使用Integer.parseInt()將其解析爲int,則可以使用'sc.next()'。上面的代碼只是一種方法,如果你願意的話,你可以使用'String',儘管你必須處理它們 – thegauravmahawar