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

时间:2015-11-20 22:48:25

标签: java arraylist while-loop

   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类的一个对象的所有信息。我想要做的是读取文本文件的一行,将信息添加到数组列表,然后使用该列表来完成我的学生构造函数的所有字段。此方法没有红线,但运行此方法时出现以下错误:

  

线程中的异常&#34; main&#34; java.lang.ClassCastException:   [Ljava.lang.String;无法转换为java.lang.String   step1.PeopleBag.importStudent(PeopleBag.java:35)at   step1.Demo.main(Demo.java:10)

2 个答案:

答案 0 :(得分:3)

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];
// ...

答案 1 :(得分:0)

或者这样做是因为split返回一个数组,你应该指定数组的索引

 tokensList.add(Arrays.asList(readFile.nextLine().split(",")[0]));