1

编辑:

我不知道如何实现return语句

不幸的是,我不知道如何实现 return 语句。哪个是问题(MPFP Book 2005)

该程序旨在增加时间。例如,将 1 小时 40 分钟添加到 2:20 ~ 使用存储新时间的传统二维数组得到 4:00 。

我的问题是我不知道如何将整数“newminutes”和“newhours”附加到二维数组以及以标准时间形式正确返回。

public class AddingTime {

    private static int [] [] nativeClockAdd (int oldHours,int oldMinutes,int addHours,int addMinutes)
    {
        int newMinutes = 0, newHours = 0;

        int[][] time = new int [newMinutes] [newHours]; // return a time.   


    newMinutes = oldMinutes + addMinutes;

    while (newMinutes > 60) // subtract 60 minutes, add an hour
    {
    newMinutes -= 60;
    addHours += 1;
    }
    newHours = oldHours + addHours;

    while (newHours > 12)
    {
    newHours -= 12; 
    }   
    return time;
    }

    public static void main(String[] args) {
        System.out.println (nativeClockAdd(4,5,7,8));

    }
}
4

2 回答 2

3
while (newMinutes > 60) // subtract 60 minutes, add an hour
{
    newMinutes -= 60;
    addHours += 1;
}
newHours = oldHours + addHours;

while (newHours > 12)
{
    newHours -= 12; 
}

这一点都不好。阅读模数运算符。所有这些循环都可以在几行中完成。

newMinutes = oldMinutes + addMinutes;           //add minutes
newHours = oldHours + addHours + newMinutes/60; //int truncation is ok, 61/60 = 1
newHours = newHours % 12; //convert to 12hr format
if(newHours == 0) { //12 % 12 is 0, set it back to 12 if that's the case
    newHours = 12;
}

如果您想更轻松地做到这一点,请为 Time 创建一个类,它只是一对表示小时和分钟的整数。你可以返回这个对象而不是一个奇怪的 int[2]。

class MyTime {
    private int minutes;
    private int hours;
    //Make this public if you think you'll need it.
    private MyTime(int h, int m) {
       this.hours = h;
       this.minutes = m;
    }

    public int getMinutes() { return minutes; }
    public int getHours() { return hours; }

    public static MyTime AddTime(int h, int m, int elapsedHours, int elapsedMinutes) {
        m += elapsedMinutes;         //add minutes
        h += elapsedHours + (m/60);  //add hours + the possible hour from minutes. integer truncation here is good. 61/60 = 1
        m = m%60;                    //get rid of excess minutes. 60 becomes 0, 61 becomes 1, etc...
        return new MyTime(h, m);
    }

    //I'm not sure if this will compile.
    /*
    public static int[2] AddTimeWeird(int h, int m, int elapsedHours, int elapsedMinutes) {
        MyTime myTime = AddTime(h, m, elapsedHours, elapsedMinutes);
        int time[] = new int[2];
        time[0] = myTime.getHours();
        time[1] = myTime.getMinutes();
        return time;
    }
    */
}
于 2013-07-31T18:40:55.133 回答
1

创建一个代表时间的类,并存储一个数组而不是原始数组。我会在这个时间类中使用双精度,并将其存储在内部的某个预定义单元中。然后,创建以其他单位返回它的方法,如下所示:

public class Time{
    private double minutes;
    public double getHours(){
        return this.minutes/60;
    }
    public double getMinutes(){
        return this.minutes;
    }
    public void add(Time time){
        this.minutes+=time.minutes;
    }
    //etc
}
于 2013-07-31T18:22:43.893 回答