不确定如何在线程“ main”中导航异常java.util.NoSuchElementException错误

问题描述 投票:-1回答:1

我正在制作一个程序,该程序遍历文件输入的每个字符串,并在文件中的名称和性别与程序用户输入的内容匹配时停止,但是我一直在线程“ main” java中得到“ Exception”。 util.NoSearchlementException错误”,我不确定这是什么以及如何解决。

代码:

import java.awt.*;
import java.util.*;
import java.io.*;

public class Draft {

   public static void main(String[] args) throws FileNotFoundException {
      Scanner console = new Scanner(System.in);
      Scanner input = new Scanner(new File("names.txt"));

      ProgramIntro();

      System.out.print("name? ");
      String userName = console.nextLine();
      System.out.print("sex (M or F)? ");
      String userGender = console.nextLine();

      while (input.hasNextLine()) {
         String line = input.nextLine();
         Scanner lineScan = new Scanner(line);
         while (lineScan.hasNext()) {
            String babyName = lineScan.next();
            String gender = lineScan.next();
            if (userName.equalsIgnoreCase(babyName) && userGender.equalsIgnoreCase(gender)) {
               System.out.print(babyName);
            }
         }
      }
   }

   public static void ProgramIntro () {
      System.out.println("This program allows you to search through the");
      System.out.println("data from the Social Security Administration");
      System.out.println("to see how popular a particular name has been");
      System.out.println("since 1920.");
   }

   public static String babyName (Scanner console) {
      System.out.print("name? ");
      String babyName = console.nextLine();
      return babyName;
   } 

}

输出:

This program allows you to search through the
data from the Social Security Administration
to see how popular a particular name has been
since 1920.
name? claire
sex (M or F)? f
Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.Scanner.throwFor(Scanner.java:937)
    at java.base/java.util.Scanner.next(Scanner.java:1478)
    at Draft.main(Draft.java:32)
java file java.util.scanner file-processing
1个回答
0
投票

[在第30行,您检查该行中是否还有另一个标记,但是随后您去从中读取了两个标记(第31和32行)。例外是告诉您实际上该行中只有一个令牌,因此您的第二次读取失败。

© www.soinside.com 2019 - 2024. All rights reserved.