获得特定的arraylist元素

时间:2013-09-29 13:01:31

标签: java

**主持人可以删除或锁定这个问题,我现在知道答案,我没有清楚地问每个问题

好抱歉生病了我的代码中的所有内容

import java.util.*;
import java.lang.*;
import java.io.*;

public class MinorAssignment_PartB {

    public static void main(String[] args) throws Exception {
        List<StudentMarks> marks = new ArrayList<StudentMarks>();
        String File = "studentinfo.txt";
        Scanner scan = new Scanner(new File(File));
        scan.useDelimiter(",");//makes the delimiter a comma

        while(scan.hasNext()) {
            marks.add(new StudentMarks(scan.next(), scan.next(),
                            scan.nextDouble(), scan.nextDouble(),
                            scan.nextDouble(), scan.nextDouble()));

            System.out.printf("%-23s %-15s %-15s %-15s " +
                    "%-15s %-15s %-15s %-15s %n", "STUDENT  NAME",
                        "STUDENT FAN", "PART A", "PART B", "PARTt C",
                                            "PART D", "MARK", "GRADE");

            for (int i = 0; i < marks.size(); i++) {
                System.out.println(marks.get(i));
            }
        }

和班级

import java.text.*;

public class StudentMarks {

    //contains a student class and an array of doubles. 
    private Student student = new Student();
    private double marks[] = new double[5];
    DecimalFormat fmt = new DecimalFormat("0.##");

    public StudentMarks(String name, String fan,
            double partA, double partB, double partC, double partD) {
        Student stud = new Student(name, fan);
        this.student = stud;
        this.marks[0] = partA;
        this.marks[1] = partB;
        this.marks[2] = partC;
        this.marks[3] = partD;
        this.marks[4] = ((partA*0.1) + (partB*0.4) + (partC*0.2) + (partD*0.3));
    }

    @Override
    public String toString() {
        return "" + student + "\t" + marks[0] + "\t\t" + marks[1] + "\t\t" + marks[2] + "\t\t" + marks[3] + "\t\t" + fmt.format(marks[4])+"%";
    }
}

所以我需要在一个arraylist

行中获得一个特定的元素

我有10行文字,每行包含2个字符串和2个双打像这样 Adam Adamson adam0001 85.4 79.8 82.4 86.1 另外9行具有相同的格式不同的名称和数字

我有marks.get(0)打印第一行,但我只需要第3个元素,85.4

感谢大家尝试,但我想通了,抱歉没有问清楚

3 个答案:

答案 0 :(得分:1)

首先,您必须添加以下getter才能访问marks中的StudentMarks;

public double[] getMarks() {
    return this.marks;
}

然后,您可以使用以下代码段来获取值85.4,即partA

StudentMarks info = marks.get(0);
double[] marksValue = info.getMarks();
double partA = marksValue[0];

partA是值85.4的必需变量,您可以根据自己的要求使用该变量。

答案 1 :(得分:0)

尝试转换

Person person =(person)marks.get(0);
System.out.println(person.StudentMarks[0]);

然后获取您需要的属性

答案 2 :(得分:0)

StudentMarks班级中定义一个getter方法:

public double[] getMarks() {
    return marks;
}

如果System.out.println(marks.get(i).getMarks()[0]);是您需要的值,请使用marks[0]