Error handling is not occurring

Asked

Viewed 59 times

2

In the code below I treated the error only that after treating it still appears the quantity name (I sent the photo below to facilitate understanding). How do I make him not show the quantity name? I would also like to know if in case an exception occurred the user had another chance to write the price again.

    System.out.println("NOME DO PRODUTO: ");
    produto.setNome(entrada.next().trim().replace(" ", "").toUpperCase());
    try {
    System.out.print("PREÇO: ");
    produto.setPreco(entrada.nextDouble());
    }catch(java.util.InputMismatchException e) {
        System.out.print("ERRO");
    }
    System.out.print("QUANTIDADE: ");
    item.setQuantidade(entrada.nextInt());

erro ocorrendo no código

  • 1

    Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site

1 answer

3

You have to put all the code you want to be dealt with inside the try, what is outside does not have this "protection" and breaks the application.

System.out.println("NOME DO PRODUTO: ");
produto.setNome(entrada.next().trim().replace(" ", "").toUpperCase());
try {
    System.out.print("PREÇO: ");
    produto.setPreco(entrada.nextDouble());
    System.out.print("QUANTIDADE: ");
    item.setQuantidade(entrada.nextInt());
} catch (java.util.InputMismatchException e) {
    System.out.print("ERRO");
}

I put in the Github for future reference.

Probably there are other problems in this code and there are visible inefficiencies, but then to see all this would need to see how the programming really works, can not be in trial and error.

Browser other questions tagged

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