Handle invalid characters inside a switch

Asked

Viewed 87 times

0

hello, I have a code that registers people and performs some functions according to the option selected in the menu that opens at the beginning of the program, the options go from 1 to 7, the problem is that if I put any other character outside those menu the program breaks, How can I fix that mistake? It is a bit disorganized yet, it has other classes but are only get and set methods to record information within the lists.

package pacotinho;

import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Collections;

public class NewClass {

public static void menu() {
    System.out.println("\n Escolha uma das seguintes opções:\n\n"
            + " 1 - Inserir dados\n"
            + " 2 - Consultar dados cadastrados\n"
            + " 3 - Sair\n"
            + " 4 - nome Crescente\n"
            + " 5 - nome Crescente, idade Crescente\n"
            + " 6 - nome Decrescente, idade Decrescente, profissao Crescente\n"
            + " 7 - Verificar se existe algo dentro das listas");

    System.out.print(" Opção escolhida: ");
}

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    List<String> teste = new ArrayList<String>(3);
    List<String> teste1 = new ArrayList<String>(3);
    List<String> teste2 = new ArrayList<String>(3);
    DecimalFormat df = new DecimalFormat("000");
    Relatorio relatorio = new Relatorio();
    Relatorio1 relatorio1 = new Relatorio1();
    Relatorio2 relatorio2 = new Relatorio2();

    int opcao;

    while (true) {
        menu();

        opcao = scan.nextInt();

        switch (opcao) {
            case 1:
                scan.nextLine();
                for (int i = 0; i <= 3; i++) {
                    System.out.print("\n\t\t\t\t\t Nome: ");
                    relatorio.setNome(scan.nextLine());
                    relatorio.listagem(opcao);
                    System.out.print("\n\t\t\t\t\t Idade: ");
                    relatorio1.setIdade(scan.nextLine());
                    relatorio1.listagem(opcao);
                    System.out.print("\n\t\t\t\t\t Profissão: ");
                    relatorio2.setProfi(scan.nextLine());
                    relatorio2.listagem(opcao);
                }
                break;
            case 2:
                teste.addAll(relatorio.listagem(opcao));
                teste1.addAll(relatorio1.listagem(opcao));
                teste2.addAll(relatorio2.listagem(opcao));
                System.out.println("\t\t\t\t\t _____________________________________________");
                System.out.println("\t\t\t\t\t                  DADOS");
                System.out.println("\t\t\t\t\t _____________________________________________");
                for (int i = 0; i < teste.size(); i++) {
                    System.out.println("\t\t\t\t\t " + df.format((i + 1)) + " " + teste.get(i) + " " + teste1.get(i) + " " + teste2.get(i));
                }

                System.out.println("\t\t\t\t\t _____________________________________________\n\n");
                System.exit(0);
                break;
            case 3:
                System.exit(0);
                break;
            case 4:
                teste.addAll(relatorio.listagem(opcao));
                teste1.addAll(relatorio1.listagem(opcao));
                teste2.addAll(relatorio2.listagem(opcao));
                System.out.println("\t\t\t\t\t _____________________________________________");
                System.out.println("\t\t\t\t\t                  NOME CRESCENTE");
                System.out.println("\t\t\t\t\t _____________________________________________");
                Collections.sort(teste);                
                for (int i = 0; i < teste.size(); i++) {                       
                    System.out.println("\t\t\t\t\t" + " " + teste.get(i));
                }

                System.out.println("\t\t\t\t\t _____________________________________________\n\n");
                System.exit(0);
                break;
            case 5:
                teste.addAll(relatorio.listagem(opcao));
                teste1.addAll(relatorio1.listagem(opcao));
                teste2.addAll(relatorio2.listagem(opcao));
                System.out.println("\t\t\t\t\t _____________________________________________");
                System.out.println("\t\t\t\t\t                  NOME CRESCENTE, IDADE DECRESCENTE");
                System.out.println("\t\t\t\t\t _____________________________________________");
                Collections.sort(teste);
                Collections.sort(teste1, Collections.reverseOrder());
                for (int i = 0; i < teste.size(); i++) {
                    System.out.println("\t\t\t\t\t" + " " + teste.get(i) + " " + teste1.get(i));
                }

                System.out.println("\t\t\t\t\t _____________________________________________\n\n");
                System.exit(0);
                break;
            case 6:
                teste.addAll(relatorio.listagem(opcao));
                teste1.addAll(relatorio1.listagem(opcao));
                teste2.addAll(relatorio2.listagem(opcao));
                System.out.println("\t\t\t\t\t _____________________________________________");
                System.out.println("\t\t\t\t\t                  NOME DECRESCENTE, IDADE DECRESCENTE E PROFISSAO CRESCENTE ");
                System.out.println("\t\t\t\t\t _____________________________________________");
                Collections.sort(teste, Collections.reverseOrder());
                Collections.sort(teste1, Collections.reverseOrder());
                Collections.sort(teste2);
                for (int i = 0; i < teste.size(); i++) {
                    System.out.println("\t\t\t\t\t" + " " + teste.get(i) + " " + teste1.get(i) + " " + teste2.get(i));
                }

                System.out.println("\t\t\t\t\t _____________________________________________\n\n");
                System.exit(0);
                break;
            case 7:
                teste.addAll(relatorio.listagem(opcao));
                teste1.addAll(relatorio1.listagem(opcao));
                teste2.addAll(relatorio2.listagem(opcao));
                if (teste.isEmpty() && teste1.isEmpty() && teste2.isEmpty()) {
                    System.out.println("VAZIO");
                } else {
                    System.out.println("CONTEM INFORMAÇÕES NA LISTA!");
                }
                System.exit(0);
                break;
            default:
                System.out.println("\t\t\t\t\t Opção inexistente! Tente novamente.\n\n");
        }

    }

}

}

That is the mistake:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at pacotinho.NewClass.main(NewClass.java:40)
/home/arthur/.cache/netbeans/8.2/executor-snippets/run.xml:53: Java 
returned: 1
FALHA NA CONSTRUÇÃO (tempo total: 6 segundos)
  • Your error possibly is related to this line: opcao = scan.nextInt();, but can you edit your question and add the error you receive? It’s the most important information.

  • ready, error added

1 answer

1


You can force the user to enter a valid number from 1 to 7 by changing your :

opcao = scan.nextInt();

For this algorithm :

int opcao = 0;
while (opcao == 0){
     try{
         Scanner scan = new Scanner(System.in);
         opcao = scan.nextInt();
         //limita os numeros de 1 a 7
         if(!(opcao > 0 && opcao < 8)){
             throw new InputMismatchException();
         }
     } catch(InputMismatchException e) {
         System.out.println("insira um numero inteiro de 1 a 7");
     }
}

When an Inputmismatchexception error occurs, it enters the catch, when the number is not between 1 and 7, it also forces it to enter the catch.
I hope it works.

  • What would this Can value variable be? for more q i use this algorithm, it prevents to start the switch, but thank you continue to test some way to treat this error.

  • I’m sorry, the variable valueScan was actually the variable option, I had just forgotten to edit.

  • 1

    thanks for the help man.

Browser other questions tagged

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