How to validate a wrong typed data?

Asked

Viewed 335 times

1

Since I could create an exception in case the user enters an invalid option, drop in exception, an error message appears and displays the menu again for the user.

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

execução

I ask you to correct the code and show me:

public void Menu() {


            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");

                    }
                }                   
  • You don’t need to create a new question with the same content, if it hasn’t been solved, you can create comments talking about where you’ve encountered difficulties

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.

2 answers

5

In my opinion the booklet suggested in the other answer is a bad place to learn, she is one of the responsible for many people programming badly. Teaches bureaucratically, without structure and encourages bad practices.

This is a very clear case that there should be no exception. Actually in Java there is a culture of abuse of exceptions, including the use of them for data validation and release Exception indiscriminately when it should launch something more specific.

I often say that exception is the most poorly used programming mechanism nowadays (now after asynchronism). Exception should be used when it is the best resource for that case, and almost never is.

I can’t help you any more without knowing other points in the code. I don’t even know where the variables of this code came from, I think they should be local, but there’s no way to know.

Note that I have captured the exceptions that the nextInt() can launch indicating that something typed does not match the expected. I do not know if I should capture all of them. And unfortunately it’s one of the things that Java encourages when an error like this should be handled with error code, since it’s not an exceptional situation. But it would be a mistake to capture Exception because then even errors that are not misspelled would be treated this way.

Some people would rather put a condition on while, how to test whether opc is different from 6. I see no need, I think in this case it is more elegant so, although a different logic could make the condition preferable.

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 you need to understand deeply on the subject, see various views, understand the mechanics of the exception, because it exists, where it is applied wrong, thing that almost nobody does, even users here on the site who have the opportunity to see all this end up ignoring and keep doing wrong because it seems to be the simplest. When used correctly the exception is simple, when used incorrectly it becomes complex and then how no one wants something complex they use more wrong still to "simplify".

Search the site on the subject. Even have divergent opinions. Or not so much, after all it is difficult to argue that the exception should be a preferential mechanism to treat validation of errors, what may exist is a convenient way in certain scenarios.

I put in the Github for future reference.

  • 2

    Just adding that one of the ways to increase software performance is to simply take away the exceptions, because they are very expensive.

0

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

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

Example of how to cast an exception:

  • throw new Exception();

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.