[英]Try-Catch gets in a loop for my Scanner - Java
在我的 java 程序中,我問的是玩家的年齡,如果用戶在提出問題時寫了一個字符串,我需要顯示錯誤 checkError(4) 並再次詢問玩家的正確年齡,直到用戶寫一個數字。
這里的問題是當年齡是一個字符串時代碼進入循環,然后總是打印字符串“玩家年齡?”。 我在一些網站上看到如果在 while 語句中使用 in.hasNextInt() 可以解決問題,但在這種情況下,如果“check”為真,我正在運行 while
我該如何解決這個問題? 謝謝
check = true;
while (check){
try {
System.out.println("Age of the player?");
if(in.hasNextInt()){
edad = in.nextInt();
if (edad > 6 && edad < 100){
check = false;
} else {
System.out.println(checkError(3));
}
} else { }
} catch(Exception e) { // Edad is a string
System.out.println(checkError(4));
}
}
像這樣嘗試:
public static void main(String[] args) {
int edad;
boolean check = true;
Scanner in = new Scanner(System.in);
while (check) {
try {
System.out.println("Age of the player?");
if (in.hasNext()) {
String s = in.next(); //read as string
edad = Integer.parseInt(s, 10); // Convet to int and throw exception if NaN
if (edad > 6 && edad < 100) {
check = false;
}
} else {
}
} catch (NumberFormatException e) { // Edad is a string
System.out.println(e.toString());
}
}
}
甚至不玩Try/Catch更容易(我認為):
public static void main(String[] args) {
int edad = 0;
boolean check = true;
Scanner in = new Scanner(System.in);
while (check) {
System.out.println("Age of the player (6 to 100 inclusive)?");
String s = in.nextLine(); // Get User input
// Did the User provide an integer numerical value?
if (!s.matches("\\d+")) {
// Nope...
System.err.println("Invalid Entry! (" + s + "). Try Again...");
}
// Yup...
else {
edad = Integer.parseInt(s, 10); // Convert it to integer
if (edad > 6 && edad < 100) { // Check Range
check = false; // is in range. :)
}
// Is out of range...
else {
System.err.println("Age (" + edad + ") is out of range! Try Again...");
}
}
}
System.out.println("Player's Age Is: --> " + edad);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.