In my java program, I am asking which is the age of the player, if the user writes a string when it was made the question I need to show the error checkError(4) and ask again which is the correct age of the player until the user writes a number.
The problem here is that the code gets in a loop when the age is a string and then always prints the string "Age of the player?". I saw in some websites that it can be solved the problem if in the while statement I use in.hasNextInt() but in this case, I am running the while if "check" is true
How can I solve this issue? Thanks
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));
}
}
try it like this :
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());
}
}
}
It's just easier (I think) to not even play with the 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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.