修改
不幸的是我不知道如何实现return语句。问题出在哪里(MPFP Book 2005)
此计划旨在增加时间。例如。使用存储新时间的传统二维阵列,将2小时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));
}
}
答案 0 :(得分: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;
}
*/
}
答案 1 :(得分:1)
创建一个表示时间的类,并存储这些类的数组而不是基元数组。我在这个时间类中使用了一个double,并将其内部存储在某个预定义的单元中。然后,创建以其他单位返回的方法,如下所示:
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
}