How to validate a wrong digit data?

1

How could I create an exception in case the user types some invalid option, falls into exception , an error message appears and shows the menu again to the user.

I created a flag starting with true , soon after I made a while and a try-catch , when there is no exception it will read the option normally and flag will be true , if there is it falls within catch displaying an error message, but when I go to run, it shows the menu only in loop infinity.

Pleasecorrectthecodeandshowme:

publicvoidMenu(){do{System.out.println("========= MENU ========\n"+
                "1)- Cadastrar livro\n"+
                "2)- Listar livro\n"+
                "3)- Pesquisar livro\n"+
                "4)- Excluir livro\n"+
                "5)- voltar\n"+
                "6)- sair\n"+
                "=======================\n"
                );

                System.out.println("Digite a opção desejada:");

                boolean flag=false;


                while(flag) {

                    try {
                        opc=inputNumerico.nextInt();
                        flag=true;

                    }
                    catch(Exception e){
                        System.out.println("Opção inválida, digite novamente");

                    }
                }                   
    
asked by anonymous 14.07.2017 / 05:25

2 answers

5

In my opinion the handout suggested in the other answer is a lousy place to learn, it is one of the people responsible for bad programming. It teaches bureaucratically, without structure and encourages bad practices.

This is a very clear case that there should be no exception. Indeed in Java there is a culture of abuse of exceptions, including using them for data validation and Exception postings indiscriminately when you should post something more specific.

I often say that exception is the most misused programming engine nowadays . Exception should be used when it is the best resource for that case, and it almost never is.

I can not help more without knowing other points of the code. I do not know where the variables of this code came from, it seems to me that they should be local, but I can not tell.

Note that I have captured the exceptions that nextInt() can throw indicating that something typed does not match what was expected. I do not even know if I should capture all of them. And unfortunately it is one of the things that Java encourages when such an error should be handled with error code, since it is not an exceptional situation. But it would be a mistake to catch Exception because there even mistakes that are not typing would be treated this way .

Some people would prefer to put a condition on while , such as testing whether opc is different from 6. I do not see a need, I think in this case it's more elegant so, although a different logic could make the condition preferable. p>

public void Menu() {
    while (true) {
        System.out.println("========= MENU ========\n"+
        "1)- Cadastrar livro\n"+
        "2)- Listar livro\n"+
        "3)- Pesquisar livro\n"+
        "4)- Excluir livro\n"+
        "5)- voltar\n"+
        "6)- sair\n"+
        "=======================\n"
        );
        System.out.println("Digite a opção desejada:");
        try {
            opc = inputNumerico.nextInt();
        } catch (InputMismatchException | NoSuchElementException | IllegalStateException e) {
            System.out.println("Digitação inválida, tente novamente");
        }
        switch (opc) {
            case 1:
                //faz aqui a chamada para o método de cadastrar
            case 2:
                //continua fazendo para cada opção
            case 6:
                return; //aqui sai do método
            default:
                System.out.println("Opção inválida, tente novamente");
        }
    }
}

I agree with the other answer that should read a lot on the subject, but need to understand deeply about it, see various views, understand the mechanics of the exception, why it exists, where it is applied wrong, something almost nobody does , even users here on the site who have the opportunity to see all this end up ignoring and continue to do wrong because it seems to be the simplest. When used correctly the exception is simple, when used in the wrong way it becomes complex and then as no one wants something complex they use it even more wrong to "simplify".

Search the site for the subject. It even has divergent opinions. Or not so much, it's hard to argue that exception should be a preferred mechanism for handling error validation, what may exist is a convenient way in certain scenarios.

I placed GitHub for future reference .

    
14.07.2017 / 10:18
0

You can throw an exception using a throw . For you to improve your knowledge I advise you to give a read / researched how the exception handling works a good start is here .

For your problem you must create a conditional to contain the cases you want and to throw an exception when the user input is not desired. That is, when the value of opc is not fair, when it is not between 1 to 6, you must throw an exception.

Example of throwing an exception:

  • throw new Exception();

But I strongly advise you to read more about it before continuing your code, as it is a concept that you should keep in mind. As well as exception types for each type of situation, it is a bad practice to throw an exception without specifying it.

    
14.07.2017 / 08:23