创建从字符串构建对象的构造函数[JAVA]

时间:2014-04-27 18:42:10

标签: java constructor implementation

我想在类Observation中创建一个构造函数,用于从文本字符串构建对象。

public class Observation implements Comparable
{

    private int photoboxID;

    private long passingTime;

    private int speedKMprHour;

    private String carID;


    /**
     * Constructor for one line from a textfile.
     * @param oneLine is a string that describes an observation
     */
    public Observation(String oneLine)
    {
        photoboxID = Integer.parseInt(oneLine[0]);
    }

}

文本文件示例。 每一行都设置如下:

photoboxID:passingTime:speedKMprHour:carID
2:1335421861264:67:AD23415
2:1335422881262:90:AD53417

提前致谢。

1 个答案:

答案 0 :(得分:1)

您只需要拆分onLine并将值分配给各个属性。

public Observation(String oneLine)
{
        String[] splitItems = oneLine.split(":");
        this.photoboxID = Integer.valueOf(splitItems[0]);
        this.passingTime = Long.valueOf(splitItems[1]);
        this.speedKMprHour  = Integer.valueOf(splitItems[2]);
        this.carID = splitItems[4];
}