开发者

Change hours minutes and seconds

The time is set as hh:mm:ss, so time is 23:50:45, once it hits midnight it will turn to 00:00:00. A practise question for my exam has asked me to write a method to do this, is my logic right or away off, I am concerned about my if else statements

public void increment()
{
if(seconds <= 59)
{
   seconds ++;
}
else if (seconds >= 60 && minutes<= 59)
{
   seconds == 0;
   minut开发者_如何转开发es ++;
}
if(minutes >= 60 && hours <= 23)
{
   hours++;
   minutes == 0;
}
else
{
  hours == 0;
}
}


You are performing assignment operations using the '==' equivalence operator. Correct that... Instead of minutes==0;, it should read minutes = 0; and so on as you are assigning '0'. The == will evaluate to a boolean. You have also used secounds some place, instead of seconds.

See this!


You can do the same thing much easier.

public void increment() {    
    seconds ++;
    if (seconds >= 60)
    {
       seconds = 0;
       minutes ++;
    }
    if(minutes >= 60)
    {
       hours++;
       minutes = 0;
    }
    if(hours >= 24)
    {
       hours = 0;
    }
}


I think your logic is wrong...

if(secounds <= 59)
{
   seconds ++;
}

will cause seconds to go to 60... or remove the else in the else if coming right after...

As pointed out by anirudh4444, to assign to 0, you should use =, not ==

I would just remove all the <= conditions. And replace the last one as

if (hours >= 24) {
    hours =0;
}

Also, spell seconds correctly (it was misspelled in some places are correctly spelled in one place...)

Your code becomes :

public void increment()
{
seconds ++;

if (seconds >= 60)
{
   seconds = 0;
   minutes ++;
}
if(minutes >= 60)
{
   hours++;
   minutes = 0;
}
if (hours >= 24)
{
  hours = 0;
}
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜