Reputation: 13
This is a method that i made for my comp sci class:
public Time (int y, int x)
{
minute = x;
hour = y;
if (minute>59 || minute<0)
{
minute = 0;
}
if (hour>=24 || hour<0)
{
hour=0;
}
}
void addOne()
{//Adds one to the minute. Still in military time
minute++;
if (minute == 60) //Makes minute never exceeds 59 minutes. Hour is added 1 and minute is set to 0
{
minute = 0;
hour++;
if (hour==24)
{
hour=0;
}
}
}
public String convert()
{//Converts to standard time with am and pm
String timer = null;
int counter = 0;
if (hour<12)
{
if (hour<9)
{
if (minute>9)
{
timer = "0"+hour+":"+minute+" A.M.";
}
if (minute<10)
{
timer = "0"+hour+":0"+minute+" A.M";
}
}
if (hour>9)
{
if (minute>9)
{
timer = ""+hour+":"+minute+" A.M.";
}
if (minute<10)
{
timer = ""+hour+":0"+minute+" A.M";
}
}
}
if (hour ==12)
{
if (minute>9)
{
timer = ""+hour+":"+minute+" P.M.";
}
if (minute<10)
{
timer = ""+hour+":0"+minute+" P.M";
}
}
if (hour>12)
{
hour-=12;
if (hour ==12)
{
if (minute>9)
{
timer = ""+hour+":"+minute+" A.M.";
}
if (minute<10)
{
timer = ""+hour+":0"+minute+" A.M";
}
}
if (hour<9)
{
if (minute>9)
{
timer = "0"+hour+":"+minute+" P.M.";
}
if (minute<10)
{
timer = "0"+hour+":0"+minute+" P.M";
}
}
if (hour>9)
{
if (minute>9)
{
timer = ""+hour+":"+minute+" P.M.";
}
if (minute<10)
{
timer = ""+hour+":0"+minute+" P.M";
}
}
}
return timer;
}
And this is the code that is suppose to run:
Time time7 = new Time(23,59);
System.out.println("\ntime7: " + time7);
System.out.println("convert time7: " + time7.convert());
time7.addOne();
System.out.println("increment time7: " + time7);
System.out.println("convert time7: " + time7.convert());
I get the output as:
time7: 2359
convert time7: 11:59 P.M.
increment time7: 1200
convert time7: 12:00 P.M
But I need the output to be:
time7: 2359
convert time7: 11:59 P.M.
increment time7: 0000
convert time7: 12:00 A.M
All other parts to the program works just fine, until i get to time7
.
Upvotes: 0
Views: 58
Reputation: 5755
After you increment and before you convert, you could add:
hour %= 24;
If hour is 24, it would then become 0.
Upvotes: 0
Reputation: 86774
Starting with hour
set to 23, then after this code:
if (hour>12)
{
hour-=12;
...
what is the value of hour
?
I'm afraid your code is needlessly complex, even if you fix the bug. Look at the String.format()
method for a much better way of formatting numbers for output that does not require you to handle all those "special cases" separately.
Upvotes: 3