Scanner not asking for input , throws No Such Elem

2019-08-03 03:48发布

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;
}

2条回答
叛逆
2楼-- · 2019-08-03 04:19

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

查看更多
霸刀☆藐视天下
3楼-- · 2019-08-03 04:30

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.

查看更多
登录 后发表回答