在不同的类中返回并显示ArrayList的内容?

时间:2017-09-11 01:23:25

标签: java arraylist

我正在开展一个项目,在那里我会计算学生的选择并将它们添加到一个计数数组中(仍然在这部分工作)。目前,我正在尝试检索已发送的选项并将其添加到Student类中的Student ArrayList。

学生班:

public class Students {

private String name;
private ArrayList<Integer> choices = new ArrayList<Integer>();


public Students(){
    name = " ";
}

public Students(String Name){
    name = Name;
}

public void setName(String Name){
    name = Name;
}

public String getName(){
    return name;
}

public void addChoices(int Choices){
    choices.add(Choices);
}

public ArrayList<Integer> getChoices(){
    return choices;
}

这是我的主要驱动程序类:

public class P1Driver {

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

    ArrayList<Students> students = new ArrayList<Students>();
    String[] choices = new String[100];
    int[] count;
    Scanner scan1 = new Scanner(new File("Choices.txt"));
    Scanner scan2 = new Scanner(new File("EitherOr.csv"));

    // Scan the first file.
    int choicesIndex = 0;
    while(scan1.hasNextLine()){
        String line = scan1.nextLine();
        choices[choicesIndex] = line;
        choicesIndex++;
    }
    scan1.close();

    // Scan the second file.
    int studentIndex = 0;
    while(scan2.hasNextLine()){
        String line = scan2.nextLine();
        String [] splits = line.split(","); 

        students.add(new Students(splits[0]));

        for(int i = 1; i < splits.length; i++){
            students.get(studentIndex).addChoices(Integer.parseInt(splits[i]));
        }
        studentIndex++;
    }
    scan2.close();

    // Instantiate and add to the count array.
    int countIndex = 0;
    for(int i = 0; i < students.size(); i++){
        if(students.get(i).getChoices(i) == -1){

        }
    }

最后一部分是我现在的位置。它显然没有接近完成(我正好在它的中间)但是在我构建一个for循环以获得学生的选择时,我得到一个错误,上面写着<, strong>&#34;学生类型中的方法getChoices()不适用于参数(int)。&#34; 有人可以解释这意味着什么,我的错误是什么,以及可能的解决方法它?谢谢大家。

2 个答案:

答案 0 :(得分:0)

您是否尝试过getChoices()[i]而不是getChoices(i)

答案 1 :(得分:0)

getChoices(int i)不是您定义的方法。

if(students.get(i).getChoices(i) == -1){

}

getChoices()会返回一个列表,因此您只需使用列表中的get方法:

if(students.get(i).getChoices().get(i) == -1){

}

或者,制作getChoice方法:

public Integer getChoice(int i){
    return choices.get(i);
}
相关问题