使用java.util.Scanner的线程“ main”中的异常java.util.NoSuchElementException

时间:2019-10-16 11:49:12

标签: java exception java.util.scanner

我当前在代码中遇到一些异常,并且不确定如何解决错误。我试图使用Scanner类Java收集用户输入,但是每当我使用它时,控制台都会显示:

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;
  }
}

我正在使用Eclipse,它显示类中的任何东西实际上都不正确,并且据我了解,没有资源泄漏会导致此问题。我已经花了很多时间尝试解决此问题,但是我无法解决它。

我测试了相同的代码,并且可以在另一个类文件上完美运行,但是在主文件中有一些干扰。如果我从另一个类文件中静态引用该代码,则该问题无法解决,并且显示相同的异常消息。

代码如下:

$data = 1, 2, 3, 2, 1
$hash = @{}
$indexes = for ($i = 0; $i -lt $data.Count; $i++) {
    # the value you store in the $hash in the else block is not important
    if ($hash.ContainsKey($data[$i])) { $i } else {$hash[$data[$i]] = $true}
}
$indexes

非常感谢您的帮助。谢谢。

编辑:删除userInput.close();在代码顶部附近进行了修复。也将意识到我有多个userInputs。感谢您的答复!

1 个答案:

答案 0 :(得分:0)

实例化一个新的inputFile.next()时,您正在做大量的Driver。每个人消耗一个元素。只需在开始时将其一次分配给一个变量,然后使用该变量即可。