With try and catch, the computer knows when something went wrong? Is there a way that in a boolean? or how can I make this loop go on as long as I get an exception?
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = 0;
System.out.println("Ingresa un número entero entro 0 y 100");
//do{
try {
x = Integer.parseInt(scan.nextLine());
}
catch(NumberFormatException e){
System.out.println("No se ha introducido un valor numérico.\nVuelva a intentarlo:");
}
//}while (x scan gets no Integer Input);
}
To use boolean
(or some other value) value as loop condition, you should declare it outside try-catch
:
Scanner scan = new Scanner(System.in);
boolean b; // <- your boolean
int x = 0;
System.out.println("Enter a number 0 y 100");
do {
try {
x = Integer.parseInt(scan.nextLine());
b = false; // <- if ok, set false
} catch(NumberFormatException e){
System.out.println("This is not a number. Please retry");
b = true; // <- if catch block is entered, set true
}
} while (b);
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.