addcruise()--nosuchelementexception:找不到行

u2nhd7ah  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(197)

我不想重温以前的主题,但我正在为一门课程做一个项目,我在一个特定的片段中反复遇到这个错误,在这个片段中,我有许多其他相同格式的代码,这些代码丝毫没有给我带来悲伤。

public static void addCruise() {

    Scanner newCruiseInput = new Scanner(System.in);
    System.out.print("Enter the name of the new cruise: ");
    String newCruiseName = newCruiseInput.nextLine();

    // Verify no cruise of same name already exists
    for (Cruise eachCruise: cruiseList) {
        if (eachCruise.getCruiseName().equalsIgnoreCase(newCruiseName)) {
            System.out.println("A cruise by that name already exists. Exiting to menu...");
            return; // Quits addCruise() method processing
        }
    }

    // Get name of cruise ship
    Scanner cruiseShipInput = new Scanner(System.in);
    System.out.print("Enter name of cruise ship: ");
    String cruiseShipName = cruiseShipInput.nextLine();
    cruiseShipInput.close();

    // Get port of departure
    Scanner cruiseDepartureInput = new Scanner(System.in);
    System.out.print("Enter cruise's departure port: ");
    String departPort = cruiseDepartureInput.nextLine();
    cruiseDepartureInput.close();

所以,如上所述,在那之前我对任何事情都没有意见 cruiseDepartureInput 扫描仪。但在我为那行提供输入之前,eclipse抛出了一个错误,它的全文如下:
在线程“main”java.util.nosuchelementexception中输入cruise的出发港:exception:找不到行
在java.base/java.util.scanner.nextline(scanner。java:1651)
在driver.addcruise(驾驶员。java:295)
在driver.main(驱动程序。java:38)
为什么我会在这里面对这个例外,而不是在程序的其他地方?其他一切都按预期进行了测试和运行,但这种特殊的输入正在变成一个令人头痛的问题。
另外,请原谅我的错误格式,我所能做的就是编辑很少愿意合作

0lvr5msh

0lvr5msh1#

删除此行,您将注意到您的问题将消失(目前):

cruiseShipInput.close();

这里的问题是你正在关闭 System.in 流,这意味着您不能再接受任何输入。所以当你尝试用 System.in 它将失败,因为流不再存在。
对于一个简单的项目,正确的答案是不要关闭扫描仪,或者最好只创建一个在整个项目中使用的扫描仪:

public static void addCruise() {

    //Create a single scanner that you can use throughout your project.
    //If you have multiple classes then need to use input then create a wrapper class to manage the scanner inputs
    Scanner inputScanner = new Scanner(System.in);

    //Now do the rest of your inputs
    System.out.print("Enter the name of the new cruise: ");
    String newCruiseName = inputScanner.nextLine();

    // Verify no cruise of same name already exists
    for (Cruise eachCruise: cruiseList) {
        if (eachCruise.getCruiseName().equalsIgnoreCase(newCruiseName)) {
            System.out.println("A cruise by that name already exists. Exiting to menu...");
            return; // Quits addCruise() method processing
        }
    }

    // Get name of cruise ship
    System.out.print("Enter name of cruise ship: ");
    String cruiseShipName = inputScanner.nextLine();

    // Get port of departure
    System.out.print("Enter cruise's departure port: ");
    String departPort = inputScanner.nextLine();

相关问题