Reputation: 123
Struggling with some java homework, why isn't this working? Advance brings in minutes. If its over 59 minutes then it adds to my hourly counter. Then I check to see if hours count over 12 to change the AM/PM status. This needs to repeatedly bring in numbers and continually add. I left out the other code as this is the part I'm supposed to be able to do.
public void advance(int advance) {
int whichAmPm = 0;
minute += advance;
if (minute > 59) {
hour++;
minute = (minute - 60);
}
if (hour > 12) {
hour = (hour - 12);
whichAmPm++;
}
if (whichAmPm % 2 == 0) {
amPm = amPm;
} else if (whichAmPm % 2 !=0) {
if (amPm == "AM") {
amPm = amPm.replaceAll("A", "P");
} else {
amPm = amPm.replaceAll("P", "A");
}
}
}
Upvotes: 1
Views: 1904
Reputation: 201447
You need to loop (instead of using if
statements). You can use -=
(like x -= y
) instead of x = x - y
. And you compare Object
types (like String
) with .equals
, ==
tests reference equality. Finally, you might use a ternary operator. I think you wanted something like,
public void advance(int advance) {
int whichAmPm = 0;
minute += advance;
while (minute > 59) {
hour++;
minute -= 60;
if (hour > 12) { // <-- this is safe because the above increments hour once
hour -= 12;
whichAmPm++;
}
}
if (whichAmPm % 2 != 0) {
amPm = amPm.equals("AM") ? "PM" : "AM";
}
}
Upvotes: 1
Reputation: 2706
The problem with your method is that it won't work when you add 120 minutes. This is a simple way to achieve what you want with no if statements.
public static final int AM = 0, PM = 1;
int hour = 0, minute = 0;
int am_pm = AM;
public void advance(int advance) {
minute += advance;
hour += minute / 60;
minute %= 60;
am_pm ^= (hour / 12 % 2);
hour %= 12;
}
Upvotes: 1
Reputation: 347244
You could simply use some modular mathematics (but one can't discount the simplicity of a loop either)
int hour = 8;
int min = 30;
int advance = 125;
min += advance % 60;
hour += advance / 60;
I'd also consider simplifying your am/pm decisions from...
if (hour > 12) {
hour = (hour - 12);
whichAmPm++;
}
if (whichAmPm % 2 == 0) {
amPm = amPm;
} else if (whichAmPm % 2 != 0) {
if (amPm == "AM") {
amPm = amPm.replaceAll("A", "P");
} else {
amPm = amPm.replaceAll("P", "A");
}
}
to something more like...
if (hour > 12) {
hour = (hour - 12);
amPm = "PM";
} else {
ampPM = "AM";
}
But that's just me
Upvotes: 1