简体   繁体   中英

ArrayList - Storing multiple values from objects in the ArrayList

I am trying to create an ArrayList to hold two integer values corresponding to diastolic and systolic blood pressure and the date at which they were taking. I have come up with the following code to hold the data in an ArrayList but it does not seem to print out.

Present readout:

94 61

I would like the readout to be:

94 61 2/12/2013

Please can someone help.

public class Blood {

private int systolic;
private int diastolic;

private int num1;
private int num2;
private int num3;
private Day day;

public Blood(int systolic, int diastolic, Day day)
{
    this.systolic = systolic;
    this.diastolic = diastolic;
    this.day = new Day(num1, num2, num3);
}

public String toString()
{
    return String.format("%s %s", systolic,diastolic);
}


public class Day {
private int num1;
private int num2;
private int num3;

public Day(int num1, int num2, int num3)
{
    this.num1 = num1;
    this.num2= num2;
    this.num3 = num3;
}

public String toString()
{
    return String.format("%d%s%d%s%d",num1,"/", num2, "/", num3);
}

import java.sql.Date;
import java.util.ArrayList;

public class BloodTest {

public static void main(String[] args) {

    ArrayList<Blood>mary = new ArrayList<Blood>();
    mary.add(new Blood(94, 61, new Day(2,12,2013)));

    System.out.println(mary.get(0));
}
}

First of all, you forgot to invoke the toString() method of Day object in your Blood object:

public class Blood {
    ...

    public String toString() {
        return String.format("%s %s", systolic,diastolic) + day.toString();
    }

    ...
}

Also you have to change the Blood constructor. You already passing in the instance of Day object, so assign it to the day field:

public Blood(int systolic, int diastolic, Day day) {
    this.systolic = systolic;
    this.diastolic = diastolic;
    this.day = day;
}

to get this to printout you would want to do this:

public static void main(String[] args) {

    ArrayList<Blood>mary = new ArrayList<Blood>();
    mary.add(new Blood(94, 61, new Day(2,12,2013)));

    System.out.println(mary.get(0).toString());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM