Search code examples
javamenucharswitch-statementdo-while

How to do a switch menu in java with do while


Good day!

This is my switch menu for a project in java!

When I put a diferent letter (letter that it´s not in the switch) I get this error message, and when I try one of the correct letter I get the same error message again:

Exception in thread "main" java.util.NoSuchElementException
        at java.base/java.util.Scanner.throwFor(Scanner.java:937)
        at java.base/java.util.Scanner.next(Scanner.java:1478)
        at teste.menu(teste.java:65)
        at teste.main(teste.java:16)

This is my code:

import java.util.Scanner;

public class teste{
  public static void main(String[] args){

    char ch;
    do {
      ch = menu();
      switch (ch){
        case 'a':
          //String name ="resultado.csv";
          //ReadFile(name);
          break;
        case 'b':
          //WriteFile();
          break;
        case 'c':
          System.out.println("nome");
          break;
        case 'd':
          System.out.println("nome");
          break;
        case 'e':
          System.out.println("nome");
          break;
        case 'f':
          System.out.println("nome");
          break;
        case 'g':
          System.out.println("nome");
          break;
        case 'h':
          System.out.println("nome");
          break;
        default:
          System.out.println("a-k!");
          break;
      }
    }while (ch != 'k');

    System.exit(0);

  }

  public static char menu(){
    System.out.println("Chose: ");
    System.out.println("a: Show");
    System.out.println("b: Write");
    System.out.println("c: All Numbers Are the Same");
    System.out.println("d: Sum Between Two Integers");
    System.out.println("e: Repeat the String");
    System.out.println("f: It is Palindrome");
    System.out.println("g: Display");
    System.out.println("h: Display");
    System.out.println("k: Quit");
    System.out.println("Insira a opção: ");
    Scanner input = new Scanner(System.in);
    char ch = input.next().charAt(0);
    input.close();
    return ch;
  }

}

I tryed with numbers and I got the same error message


Solution

  • Don't recreate the scanner each time menu is called. Create it once at start of main and use it, such as:

    public static Scanner input = new Scanner(System.in);
    
    public static void main(String[] args) {
        // same code...until end of main...
        input.close();
        System.exit(0);
    }
    

    and in menu:

    public static char menu() {
        // same prompts...
    
        //REMOVE    Scanner input = new Scanner(System.in);
        char ch = input.next().charAt(0);
        //REMOVE    input.close();
        return ch;
    }