0

Im trying to do a simple menu system, but its giving me an "NoSuchElementException".

When I press option 1, it executes well, but when I call option 2 it asks me for "w" and then the exception is thrown.

I've tried adding an if (sc.hasNext) like I saw on this post, but after I call option 2, it keeps looping and doesn't let me type a value for X.

    public Main() {
    int x = 5;
    Scanner sc = new Scanner(System.in);

    while(x != 0) {
        System.out.println("########## MT ###########");
        System.out.println("# 1 - Read MT           #");
        System.out.println("# 2 - Read w            #");
        System.out.println("# 0 - Exit              #");
        System.out.println("#########################");
        System.out.print("Option: ");

        x = sc.nextInt(); //Here is the error.

        switch (x) {
        case 1:
                setMaquina(new MT());
            break;
        case 2:
                if (getMaquina() == null) {
                    System.out.println("MT is null.");
                }
                else {
                    Scanner scc = new Scanner(System.in);
                    System.out.print("    ~ w: ");

                    String w = scc.nextLine();

                    getMaquina().readString(w);

                    scc.close();
                }
            break;
        case 0:
            x = 0;
            break;
        default:
            break;
        }
    }

    sc.close();
}

EDIT

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    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 maquina.turing.Main.<init>(Main.java:26)
    at maquina.turing.Main.main(Main.java:11)
Community
  • 1
  • 1
Fran
  • 360
  • 3
  • 16
  • 1
    There is a wealth of information in a thrown exception's stacktrace. If you have one, always include it in SO questions. – arcy Oct 10 '15 at 11:26
  • Fixed it, I only removed the `scc.close()` and `sc.close()` , and now works perfectly. – Fran Oct 10 '15 at 11:37

0 Answers0