简体   繁体   中英

Scanner not asking for input , throws No Such Element Exception - multiple scanners

In the below code I have used two scanners, One in performAction() method and one in getTicketNumber() method. I have used try with resources and once when I go into getTicketNumber() method, it works fine and once when the control returns back and comes to performAction() I am getting No Such Element Exception when it executes the scanner.nextInt() line. I wanted to continue this process until I press exit. I guess it is due to the use of multiple scanners since if I don't go into getTicketNumber() method, it works fine. Any ideas?

private void performAction() {
    int choice = 4;
    System.out.println("Hi User");
    System.out.println("What do you want to do ");
    try (Scanner scanner = new Scanner(System.in)) {
        do {
            System.out.println("1. Book ticket");
            System.out.println("2. Cancel ticket");
            System.out.println("3. Check status");
            System.out.println("4. Exit");
            System.out.println("Enter your choice");
            choice = scanner.nextInt();
            System.out.println();
            doActionBasedOnChoice(choice);
            System.out.println();
        } while (choice != 4);

    } catch (InputMismatchException e) {
        System.out.println("Please enter a valid choice");
    }
}

private void doActionBasedOnChoice(int choice) {

    switch (choice) {
    case 1:
        ticketReservation.bookFlight();
        break;
    case 2:
        System.out.println("Please enter your ticket number ");
        int ticketNumber = getTicketNumber();
        ticketReservation.cancel(ticketNumber);
        break;
    case 3:
        ticketReservation.checkConfirmedListStatus();
        break;
    case 4:
        System.out.println("Thank you ");
        break;
    default:
        break;
    }
}

private int getTicketNumber() {
    try (Scanner scanner = new Scanner(System.in)) {
        int choice = scanner.nextInt();
        return choice;
    } catch (InputMismatchException e) {
        System.out.println("Please enter a valid ticekt number");
    }
    return 0;
}

When the "inner" scanner passes out of scope, it is disposed by the try-block, which in turn closes the System.in stream.

Solve by passing the scanner along to whoever needs it, or alternatively move it to a higher scope.

I figure it out that when you use try with resource it will close the resource automatically, and once the System.in is closed it cannot be reopened.
So Suggestion is use one Scanner Object and pass it via args to different methods

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM