Loop Infinite in exception handling

0

I'm trying to make a try to ask for the option number for the user, however I want to do this until he type an integer, I made a try / catch, but when he squeezes it and digit a string he keeps sending a error message several times, and I can not identify the error;

public class CaniveteSuico {

    static Scanner in = new Scanner (System.in);

    public Integer Menu() {
        int  opcao=0;
        int checar=0;
        do {
            checar=0;

            System.out.println("\n  ==================================");
            System.out.println("  |     1 - Gestão de Produtos      |");
            System.out.println("  |     2 - Gestão de Vendas        |");
            System.out.println("  |     3 - Gestão de Pessoas       |");
            System.out.println("  |     0 - Sair                    |");
            System.out.println("  ===================================\n");
            System.out.print(" Opção -> ");

            try {
                opcao = in.nextInt();  
                System.out.print("\n");
                checar =1;
            } catch(Exception e) {
                System.err.println("Você digitou um caractere inválido! Tente novamente ");
            }
        } while(checar==0);

    return opcao;
}

}

    
asked by anonymous 03.10.2018 / 04:49

1 answer

0

It turns out that there is an exception of type InputMismatchException causes content not to be consumed. So if you are trying to read an integer and the user places a text as "teste" an exception is thrown and the "teste" text is still there. This means that when you go back to nextInt to read it again, it picks up the same exception again. The solution is to clean up what was forced by a string reading for example, using nextLine :

try {
    opcao = in.nextInt();  
    System.out.print("\n");
    checar =1;
} catch(Exception e) {
    in.nextLine(); //"limpa" o que ficou por ler que não era inteiro
    System.err.println("Você digitou um caractere inválido! Tente novamente ");
}

It is important to mention that you should always capture only the exception that you are interested in and not all you are doing using Exception , because in some cases you can catch other exceptions that you would not expect and give the same treatment without to realize So I could rewrite capturing only InputMismatchException :

try {
    opcao = in.nextInt();  
    System.out.print("\n");
    checar =1;
} catch(InputMismatchException« e) {
//            ^--- captura apenas o tipo que interessa
    in.nextLine();
    System.err.println("Você digitou um caractere inválido! Tente novamente ");
}
    
03.10.2018 / 12:33