制作一个打印出军事时间并增加/减少时间的“时钟”

时间:2015-04-13 19:00:31

标签: java methods time tostring clock

我正在尝试制作一个能做一些事情的“时钟”:
1)将指定时间显示为军事时间(午夜00:00:00)
2)使用时钟对象向时钟添加或减去指定的时间,时钟对象具有最多3个整数参数(h,m,s),以及数学方法或其他时钟对象
- 例子)

System.out.print (c1 + " + 10 hours is ");
        c1.addHours(10);
        System.out.println (c1);  

- 示例2)

System.out.print (c4 + " + 12:59:55 is ");
            c4.addTime(12,59,55);
            System.out.println (c4);

所以我遇到了两件事:数学方法和toString()方法使得它全部打印出来。我对toString()方法的想法很新,但它们并没有太多意义。这是我的数学和toString()方法,任何帮助表示赞赏。

//**********Methods to perform calculations w/ an object

    public void addHours(int h){
        if(this.hours + h > 23)
            hours = this.hours + (h % 24);
        else
            hours = this.hours + h;
    }

    public void addMinutes(int m){
        if(this.mins + m > 59){
            hours = this.hours + (m % 60);
            mins = this.mins + (hours % (m % 60));
        }
        else
            mins = this.mins + m;
    }

    public void addSeconds(int s){
        if(this.secs + s > 59){
            mins = this.mins + (s % 60);
            secs = this.secs + (mins % (s % 60));
        }
        else
            secs = this.secs + s;
    }

    public void addTime(int h, int m, int s){
        addHours(h);
        addMinutes(m);
        addSeconds(s);
    }


//Displays correctly formatted time
    public String toString(){
        if(hours > 23 || hours < 0)
            return "00:00:00";
        if(hours > 9)
            return "" + getHours();
        if(mins > 9)
            return "" + getMinutes();
        if(secs > 9)
            return "" + getSeconds();

        return "0" + getHours() + ":0" + getMinutes() + ":0" + getSeconds();
    }

1 个答案:

答案 0 :(得分:0)

您的add方法不必要复杂。你可以简化它们。关于toSting():在我看来,你对return有一个普遍的误解。 return语句结束方法。如果您的程序遇到return,则不会执行方法代码的其余部分。返回后的语句(如果有)将被评估并返回。

public void addHours(int h) {
    // The "if" was semantically unnecessary
    this.hours += (h % 24);
}

public void addMinutes(int m) {
        // Forward to addHours, exploit integer arithmetics
        this.addHours(m / 60);
        this.mins += (m % 60);
}

public void addSeconds(int s) {
    // Forward to addMinutes, exploit integer arithmetics
    this.addMinutes(s / 60);
    this.secs += (s % 60);
}
[...]
//Displays correctly formatted time
public String toString() {
    if ((this.hours > 23)  || (this.hours < 0)) {
        return ("00:00:00");
    }
    String result = "";
    // Add a leading zero
    if (this.hours < 10) {
        result += "0";
    }
    result += (this.hours + ":");

    // Add a leading zero
    if (this.mins < 10) {
        result += "0";
    }
    builder.append(this.mins + ":");

    // Add a leading zero
    if (this.secs < 10) {
        result += "0";
    }
    builder.append(this.secs);

    return (result);
}

编辑:从理论上讲,可以将负值传递给add方法。如果您想要安全起见,请添加一些if - 子句以防止时间减少。