扫描仪不要求输入,不会引发此类元素异常-多个扫描仪 [英] Scanner not asking for input , throws No Such Element Exception - multiple scanners

查看:63
本文介绍了扫描仪不要求输入,不会引发此类元素异常-多个扫描仪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我使用了两个扫描仪,一个在performAction()方法中,一个在getTicketNumber()方法中.我曾经尝试过使用资源,一次当我进入getTicketNumber()方法时,它工作正常,而当一次控件返回并返回到performAction()时,我在执行scanner.nextInt()行时遇到了No Such Element Exception. .我想继续此过程,直到按退出.我想这是由于使用了多个扫描仪,因为如果我不使用getTicketNumber()方法,它就可以正常工作.有什么想法吗?

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

推荐答案

当内部"扫描程序超出范围时,它由try块处理,try块又关闭了System.in流.

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.

这篇关于扫描仪不要求输入,不会引发此类元素异常-多个扫描仪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆