简体   繁体   English

ArrayList-从ArrayList中的对象存储多个值

[英]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. 我正在尝试创建一个ArrayList来保存两个与舒张压和收缩压以及服用日期相对应的整数值。 I have come up with the following code to hold the data in an ArrayList but it does not seem to print out. 我想出了以下代码来将数据保存在ArrayList但似乎无法打印出来。

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: 首先,您忘记在Blood对象中调用Day对象的toString()方法:

public class Blood {
    ...

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

    ...
}

Also you have to change the Blood constructor. 另外,您必须更改Blood构造函数。 You already passing in the instance of Day object, so assign it to the day field: 您已经传递了Day对象的实例,因此将其分配给day字段:

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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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