簡體   English   中英

獲取特定的arraylist元素

[英]Getting a particular arraylist element

**主持人可以刪除或鎖定這個問題嗎,我現在知道答案了,但我並沒有清楚地提出問題

好吧,抱歉,我的代碼中發布了所有內容

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),它會打印第一行,但我只需要第三個元素85.4

感謝所有人的嘗試,但我想出了辦法,對不起,我沒有很清楚地提出問題

首先,您必須將以下getter添加到StudentMarks訪問marks中;

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

然后,您可以使用以下代碼段獲取值85.4partA

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

partA是必需變量,其值為85.4 ,您可以根據需要使用它。

嘗試轉換

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

然后獲取您需要的屬性

StudentMarks類中定義一個getter方法:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM