首页 > 解决方案 > 使用 java.util.Scanner 的线程“主”java.util.NoSuchElementException 中的异常

问题描述

我的代码目前面临一些异常,我不确定如何解决这些错误。我正在尝试使用 Scanner 类 Java 收集用户输入,但每当我使用它时,控制台都会显示:

1. Display Drivers
2. Import Infringement File
3. Generate Suspension Report
4. Save Driver Records
5. Exit Program
Enter a menu choice:
    Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextByte(Unknown Source)
    at java.util.Scanner.nextByte(Unknown Source)
    at code.Main.validateChoice(Main.java:109) 
    at code.Main.main(Main.java:84)

我正在使用 Eclipse,它显示我的课程中没有任何内容实际上是不正确的,并且我的理解中没有可能导致此问题的资源泄漏。我已经花了很多时间试图解决这个问题,但我无法解决它。

我测试了相同的代码,它在另一个类文件上完美运行,但在主文件中有些东西干扰了它。如果我从另一个类文件中静态引用代码,则问题不会得到解决,并且会显示相同的异常消息。

代码如下:

public class Main {
  static Scanner userInput = new Scanner(System.in);

  public static void main(String[] args) {
    // Determine Driver File Location
    String fileLocation = "Driver.txt";
    File driverFile = new File(fileLocation);
    Scanner userInput = new Scanner(System.in);

    // If cannot find driver file
    while (!driverFile.exists()) {
      System.out.println("Cannot find drivers file. \nEnter the correct file location: ");
      fileLocation = userInput.nextLine(); // enter user input for file location
    }
    driverFile = new File(fileLocation);
    userInput.close();


    // Reading From Drivers
    try { // Attempt to read from file
      Scanner inputFile = new Scanner(driverFile);
      inputFile.useDelimiter(",");
      ArrayList<Driver> drivers = new ArrayList<>();

      int counter = 0; // Set counter for each iteration
      while (inputFile.hasNext()) {
        try {
          drivers.add(
              new Driver(inputFile.nextInt(), inputFile.next(), inputFile.next(), inputFile.next(),
                  inputFile.next(), inputFile.next(), inputFile.nextShort(), inputFile.nextByte()));

          // Enter correct value of last string
          String temp = inputFile.nextLine();
          if (temp.equals(",Valid")) {
            drivers.get(counter).setLicenceStatus("Valid");
          }

          else if (temp.equals(",Suspended")) {
            drivers.get(counter).setLicenceStatus("Suspended");
          }

          else { // if input was not correct, end input and show an exception has been made
            System.out.println("Licence Status incorrect, bad data in file ");
            break;
          }

          // Data check licenceClass
          if (drivers.get(counter).verifyLicenceClass() == false) {
            System.out.println("Licence Class incorrect, bad data in file ");
            break;
          }

        } catch (InputMismatchException e) {
          System.out.println("Bad data in file ");
          break;
        } // end catch
        counter++;
      }
      inputFile.close();

    } catch (FileNotFoundException e) {
      System.out.println("The driver file was not found");
    } // end missing driver file catch


    // Menu Items
    String[] firstMenuItems = {"Display Drivers", "Import Infringement File",
        "Generate Suspension Report", "Save Driver Records", "Exit Program"};
    final int firstMinMenu = 1; // menu values
    final int firstMaxMenu = 5;

    byte choice;
    do {
      displayMenu(firstMenuItems);
      choice = (byte) validateChoice(firstMinMenu, firstMaxMenu);
      // System.out.println("Your menu choice was " + choice);
    } while (choice != firstMaxMenu);


  } // end main

  /*
   * Methods
   */

  public static void displayMenu(String[] menu) {
    for (int i = 0; i < menu.length; i++) {
      System.out.println((i + 1) + ". " + menu[i]);
    }
    System.out.println("Enter a menu choice: ");
  }

  // Determine if choice is in range
  public static int validateChoice(int min, int max) {
    int input = 0;
    do {
      input = userInput.nextByte();
      if (input < min || input > max) {
        System.out.println("Please enter a menu choice in range");
      }
    } while (input < min || input > max);
    return input;
  }
}

将不胜感激任何帮助。谢谢。

编辑:删除 userInput.close(); 在代码顶部附近修复了它。也会意识到我有多个用户输入。感谢您的回复!

标签: javaexceptionjava.util.scanner

解决方案


实例inputFile.next()化一个新的Driver. 每个人消耗一个元素。只需在开始时将它分配一个变量并使用该变量。


推荐阅读