How to return Time using a 2-D array (Java)? -
edit:
unfortunately dont know how implement return statement. problem (mpfp book 2005)
this program designed add time onto time. e.g. add 1 hour , 40 minutes 2:20 ~ gives 4:00 using conventional 2-d array stores new time.
my issue not know how append integers 'newminutes' , 'newhours' onto 2-d array return in standard time form.
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 time. newminutes = oldminutes + addminutes; while (newminutes > 60) // subtract 60 minutes, add 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)); } }
while (newminutes > 60) // subtract 60 minutes, add hour { newminutes -= 60; addhours += 1; } newhours = oldhours + addhours; while (newhours > 12) { newhours -= 12; }
this not @ all. read on modulus operator. loops can done in handful of lines.
newminutes = oldminutes + addminutes; //add minutes newhours = oldhours + addhours + newminutes/60; //int truncation ok, 61/60 = 1 newhours = newhours % 12; //convert 12hr format if(newhours == 0) { //12 % 12 0, set 12 if that's case newhours = 12; }
if want more easily, create class time pair of integers hours , minutes. can return object rather weird int[2].
class mytime { private int minutes; private int hours; //make public if 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 + possible hour minutes. integer truncation here 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 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; } */ }
Comments
Post a Comment