简体   繁体   中英

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;
   minutes ++;
}
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;
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM