addCruise() -- NoSuchElementException:找不到行

addCruise() -- NoSuchElementException: No line found

不是要重温旧话题,但我正在为一门课程做一个项目,我在一个特定的部分反复遇到这个错误,我在 相同的格式,我一点也不伤心。

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 抛出了错误,完整内容如下:

输入游轮的出发港:线程“主”中的异常java.util.NoSuchElementException:找不到行

为什么我会在这里遇到这个异常,而在程序的其他地方却不会?其他一切都按预期进行了测试和运行,但这个特定的输入变得令人头疼。

此外,请原谅我的格式错误,编辑希望合作的可能性很小

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

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