【问题标题】:NoSuchElementException reading words and numbers from file [duplicate]NoSuchElementException 从文件中读取单词和数字[重复]
【发布时间】:2015-09-06 19:31:21
【问题描述】:

我正在尝试从包含多行“名称、整数月、整数日期、整数年”信息的文件中读取数据。 Person 对象将这些项目作为其构造函数参数。但是,当我尝试从文件中读取并填充列表时,我收到以下错误:

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.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at lab03.PersonSort.populate(PersonSort.java:56)
    at lab03.PersonSort.main(PersonSort.java:38)

这是我的代码:

   public static void main(String[] args) throws Exception {

    ArrayList<Person> people = new ArrayList<Person>();

    populate(people);
    //selectionSort(people);

    int index = 0;
    while (index < people.size())
    {
        System.out.println(people.get(index));
        index++;
    }

}

public static ArrayList populate(ArrayList<Person> array) {
    final String PERSON_FILE = ".\\src\\Persons.txt";
    Scanner input = new Scanner(PERSON_FILE);

    while (input.hasNext()) {
        String name = input.next();
        int month = input.nextInt();
        int day = input.nextInt();
        int year = input.nextInt();
        Person temp = new Person(name, month, day, year);
        array.add(temp);
    }

    return array;
}

persons.txt 文件有以下内容:

梅利 9 10 1998

以利亚 3 月 19 日 2013

克里斯汀 7 29 1981

安妮 8 28 2002

贝拉 8 28 2010

马特 9 11 1952

卡西迪 8 5 1997

【问题讨论】:

  • 向我们展示一个示例 Persons.txt。

标签: java file exception


【解决方案1】:

原因是您试图解析字符串“.\\src\\Persons.txt”而不是文件的内容。写Scanner input = new Scanner(new File(PERSON_FILE).toPath()); 应该可以解决它。

【讨论】:

    猜你喜欢
    • 2015-06-09
    • 1970-01-01
    • 2021-07-17
    • 2011-04-12
    • 1970-01-01
    • 2016-04-25
    • 2017-04-15
    • 2017-04-17
    • 2019-07-03
    相关资源
    最近更新 更多