0

So I have a menu for the user using switch case.

public static void app() {
    Scanner sc = new Scanner(System.in);
    List list = list.read(file.txt);
    StringBuilder menu;
    int choice = 0;
    do {
        System.out.println(menu.toString());

        choice = sc.nextInt();
        switch (choice) {
        case 1:
            option1();
            break;
        case 2:
            option2();
            break;
        case 3:
            option3(list);
            break;
        case 4:
            option4(list);
            break;
        case 5:
            break;
        default:
            break;
        }
    } while (choice != 5);
}

The first 2 options are just methods(outside this class) that allow me to add another object to the list and I don't have any trouble with those 2. Options 3/4 also work, but it causes some issue with the switch case menu.

For options 3/4 I have to ask a certain max of the user, which I do by using a Scanner, but the same int is then also used by the switch case which leads to an error.

I get an exception in the thread "main"(which is where I call the app method) which gets printed right before the menu gets printed strangely enough and I also get a NoSuchElementException at the choice=sc.nextInt() line.

I had thought about closing the scanner right before I call the methods and reopening it afterwards, but that isn't possible.

public static void option3(list input) {
    Scanner sc = new Scanner(System.in);
    System.out.println(question);
    int max = sc.nextInt();
    int size = input.size();
    if (size > 0) {
        if (max == 0) {
            print entire list
        } else {
            print list below max
        }

    }
    sc.close();

}
asiannoob
  • 33
  • 4

1 Answers1

1

You should use only one scanner for the same stream (in your case System.in). You can pass your scanner to the method and use it there:

public static void option3(list input, Scanner sc) {
    System.out.println(question);
    int max = sc.nextInt();
    int size = input.size();
    if (size > 0) {
        if (max == 0) {
            print entire list
        } else {
            print list below max
        }

    }
}

in your app() method:

  case 3:
        option3(list, sc);
        break;
giorashc
  • 13,691
  • 3
  • 35
  • 71