I am making a program which receives 2 integers by keyboard and returns the result (division), the detail is that I want that if an exception occurs (for example that a float is entered) that the program does not end there, if not, be able to ask the user for the numbers again.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Principal {
public static void main(String[] args) {
int numero1, numero2,resultado;
Scanner entrada = new Scanner(System.in);
try{
System.out.println("Ingrese el valor de a");
numero1 = entrada.nextInt();
System.out.println("Ingrese el valor de b");
numero2 = entrada.nextInt();
resultado = numero1 / numero2;
System.out.println("El resultado es: "+resultado);
}catch(InputMismatchException ex){
System.out.println("Ingreso un numero no valido, solamente se aceptan enteros");
}
}
}
This is how the running program behaves
run:
Ingrese el valor de a
5
Ingrese el valor de b
4.5
Ingreso un numero no valido, solamente se aceptan enteros
BUILD SUCCESSFUL (total time: 2 seconds)
You can create a flag that tells you when two correct numbers have already been entered. Likewise, this flag would help you to determine which number is the one that has been entered with an error.