addCruise-NoSuchElementException:找不到行

问题描述

不想重新讨论旧主题,但是我正在为一个课程设计一个项目,并且我在某个特定段反复遇到此错误,在该段中,我以相同的格式获取了许多其他代码不会给我带来任何悲伤。

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();

因此,如上所述,{em> 直到cruiseDepartureInput扫描仪都没有问题。但是在提供该行的输入之前,Eclipse抛出了错误,该错误的全文如下:

输入巡航的出发端口:线程“ main”中的异常java.util.NoSuchElementException:找不到行

  • 在java.base / java.util.Scanner.nextLine(Scanner.java:1651)
  • 在Driver.addCruise(Driver.java:295)
  • 在Driver.main(Driver.java:38)

为什么我在这里会遇到此异常,而在程序其余部分中却没有遇到?其他所有测试和功能均按预期运行,但是这种特殊的输入正变得令人头疼。

此外,请原谅我的错误格式,尽我所能,编辑器只需要很少的合作即可

解决方法

删除此行,您会发现您的问题将暂时消失(暂时):

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();