gpt4 book ai didi

java - 如何使用 while 循环用不同类型的对象填充数组列表

转载 作者:行者123 更新时间:2023-12-01 21:59:21 25 4
gpt4 key购买 nike

   public void importStudent(String fileName) throws FileNotFoundException{
File input = new File("students.txt");
Scanner readFile = new Scanner(input);
ArrayList<Object> tokensList = new ArrayList<Object>();

while (readFile.hasNextLine()){

tokensList.add(readFile.nextLine().split(","));

String FirstName = (String) tokensList.get(0);
String LastName = (String) tokensList.get(1);
String phoneNum = (String) tokensList.get(2);
String address = (String) tokensList.get(3);
double gpa = (double) tokensList.get(4);
String major = (String) tokensList.get(5);
double creditsTaking = (double) tokensList.get(6);
//all of the stuff in one line of the text file
Student s = new Student( FirstName, LastName, phoneNum, address, gpa,
major, creditsTaking);
peopleBag.add(s);
}
readFile.close();
}

所以我有一个文本文件,其中每一行都包含我尝试创建的 Student 类的一个对象的所有信息。我想要做的是读取文本文件的一行,将信息添加到数组列表中,然后使用该列表来满足我的 Student 构造函数的所有字段。该方法没有红线,但运行该方法时出现以下错误:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String at step1.PeopleBag.importStudent(PeopleBag.java:35) at step1.Demo.main(Demo.java:10)

最佳答案

String.split 返回一个数组,而不是 List。你可以像这样修复它,

List<String> tokensList = new ArrayList<>();
tokensList.add(Arrays.asList(readFile.nextLine().split(",")));

或者将tokensList更改为数组,然后像数组一样访问它。

String[] tokens = readFile.nextLine().split(",");
String FirstName = tokens[0];
// ...

关于java - 如何使用 while 循环用不同类型的对象填充数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33837336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com