这是我为comp sci课程制作的方法:
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;
}
这是要运行的代码:
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());
我得到的输出为:
时间7:2359
转换时间7:11:59 P.M。
增加时间7:1200
转换时间7:00:00 P.M
但我需要输出:
时间7:2359
转换时间7:11:59 P.M。
增加时间7:0000
转换时间7:00:00 A.M
程序的所有其他部分都运行正常,直到我到达time7
。
答案 0 :(得分:3)
从hour
设置为23开始,然后在此代码之后:
if (hour>12)
{
hour-=12;
...
hour
的价值是什么?
即使您修复了错误,我担心您的代码也会不必要地复杂化。查看String.format()
方法,以便更好地格式化输出数字,而不需要单独处理所有这些“特殊情况”。
答案 1 :(得分:0)
在增加之后和转换之前,您可以添加:
hour %= 24;
如果小时为24,那么它将变为0。