addcruise()--nosuchelementexception:找不到行

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

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

  1. public static void addCruise() {
  2. Scanner newCruiseInput = new Scanner(System.in);
  3. System.out.print("Enter the name of the new cruise: ");
  4. String newCruiseName = newCruiseInput.nextLine();
  5. // Verify no cruise of same name already exists
  6. for (Cruise eachCruise: cruiseList) {
  7. if (eachCruise.getCruiseName().equalsIgnoreCase(newCruiseName)) {
  8. System.out.println("A cruise by that name already exists. Exiting to menu...");
  9. return; // Quits addCruise() method processing
  10. }
  11. }
  12. // Get name of cruise ship
  13. Scanner cruiseShipInput = new Scanner(System.in);
  14. System.out.print("Enter name of cruise ship: ");
  15. String cruiseShipName = cruiseShipInput.nextLine();
  16. cruiseShipInput.close();
  17. // Get port of departure
  18. Scanner cruiseDepartureInput = new Scanner(System.in);
  19. System.out.print("Enter cruise's departure port: ");
  20. String departPort = cruiseDepartureInput.nextLine();
  21. 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#

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

  1. cruiseShipInput.close();

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

  1. public static void addCruise() {
  2. //Create a single scanner that you can use throughout your project.
  3. //If you have multiple classes then need to use input then create a wrapper class to manage the scanner inputs
  4. Scanner inputScanner = new Scanner(System.in);
  5. //Now do the rest of your inputs
  6. System.out.print("Enter the name of the new cruise: ");
  7. String newCruiseName = inputScanner.nextLine();
  8. // Verify no cruise of same name already exists
  9. for (Cruise eachCruise: cruiseList) {
  10. if (eachCruise.getCruiseName().equalsIgnoreCase(newCruiseName)) {
  11. System.out.println("A cruise by that name already exists. Exiting to menu...");
  12. return; // Quits addCruise() method processing
  13. }
  14. }
  15. // Get name of cruise ship
  16. System.out.print("Enter name of cruise ship: ");
  17. String cruiseShipName = inputScanner.nextLine();
  18. // Get port of departure
  19. System.out.print("Enter cruise's departure port: ");
  20. String departPort = inputScanner.nextLine();
展开查看全部

相关问题