[英]Asking for two integer values in Java and throwing errors
我有這個代碼。 它要求兩個 integer 值。 如果第一個數字不是 integer,那么它會拋出異常並再次詢問該數字。 我的代碼有效,但我想知道是否有更好的方法來做到這一點:
boolean validInput = false;
boolean validInput2 = false;
while (validInput == false) {
try {
Scanner scanner = new Scanner(System.in);
System.out.print("What is the first number? ");
int firstNum = scanner.nextInt();
validInput = true;
} catch (InputMismatchException e) {
System.out.println("It's not an integer.");
}
}
while (validInput2 == false) {
try {
Scanner scanner2 = new Scanner(System.in);
System.out.print("What is the second number? ");
int secondNum = scanner2.nextInt();
scanner2.close();
validInput2 = true;
} catch (InputMismatchException e) {
System.out.println("It's not an integer.");
}
}
我想我也可以做這樣的事情。 正確的?
while (validInput == false) {
Scanner scanner = new Scanner(System.in);
System.out.print("What is the first number? ");
if (scanner.hasNextInt()) {
int firstNum = scanner.nextInt();
validInput = true;
}
}
在第二個示例中,當調用hasNextInt()
方法時,掃描器等待一個值,這是有道理的,如果條件為真,則調用 nextInt( nextInt()
,但nextInt()
不再等待輸入。 nextInt()
如何知道條件執行時輸入的值是什么?
這是我會這樣做的方式:
int firstNum;
int secondNum;
String num;
String errMsg = "Invalid Input - Integer Only!";
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("What is the first number? ");
num = scanner.nextLine();
if (num.matches("\\d+")) {
firstNum = Integer.parseInt(num);
break;
}
System.out.println(errMsg);
}
while (true) {
System.out.print("What is the second number? ");
num = scanner.nextLine();
if (num.matches("\\d+")) {
secondNum = Integer.parseInt(num);
break;
}
System.out.println(errMsg);
}
System.out.println();
System.out.println("First Number: --> " + firstNum);
System.out.println("eacond Number: --> " + secondNum);
為了從用戶那里獲取數字輸入,我更喜歡將Scanner.nextLine()方法與String.matches()方法和一個簡單的正則表達式( "\\d+" ) 結合使用。 您不需要以這種方式捕獲異常。 我只是覺得它更靈活。
在while循環之前聲明你的變量,這樣你就可以在while循環之后使用它們,或者如果你願意,甚至可以在其他while循環中使用它們。 一旦你獲得並驗證了你需要的東西,就跳出一個循環。
使用nextInt()
后,您必須在再次嘗試nextInt()
)之前使用nextLine()
用戶按下Enter時仍然存在的換行符的輸入緩沖區,例如:
System.out.print("What is the first number? ");
int firstNum = scanner.nextInt();
scanner.nextLine(); // <-- add this line
更好的是一口氣讀入整行並將其解析為 integer :
int firstNum = Integer.parseInt(scanner.nextLine()); // do it in 1 line
再好一點是編寫一個可重用的方法,不斷嘗試解析 integer,如果它沒有讀取有效的 integer,請讓用戶重試(留給讀者實現)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.