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

坚强是说给别人听的谎言 提交于 2019-12-11 10:37:10

问题


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

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/52620428/scanner-not-asking-for-input-throws-no-such-element-exception-multiple-scann

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!