开发者

Require some help with Java

开发者 https://www.devze.com 2022-12-12 07:47 出处:网络
Use of if to simulate modulus operator Rewrite this increment() method from the NumberDisplay() class without using the % modulus operator.

Use of if to simulate modulus operator

Rewrite this increment() method from the NumberDisplay() class without using the % modulus operator.

/** Increment the display value by one *  rolling over to zero if the limit is reached  */
public void increment() 
{
   if(value > limit);
   else
   value = (value + 1);
   value = 0;
}

well, i tested this out, i put开发者_JAVA百科 value = (value + 1); it complied sucessfully, but the error came up as rollover was less then the amount. any help would be great!


You're always assigning 0 to value, unconditionally. You've also got an empty "if" statement, which isn't a good sign - and hard to spot as you've just used ";" instead of braces.

Here's your current code rewritten with braces:

public void increment() 
{
   if(value > limit)
   {
   }
   else
   {
       value = (value + 1);
   }
   value = 0;
}

Now, rather than show you the code itself, I'll give you two hints:

  • How would value ever be strictly greater than the limit?
  • Why would you not want to change value at all if it's particularly high? What would you want it to become instead?


Without thinking in terms of code syntax and such, try to read what you put as if it were an English sentence. That should give you some idea, e.g.:

If the value is greater than the limit, then ...


I suggest you read how to properly write an if statement.


Hint: watch out for semicolons in strange places.

Hint 2: try using { and } with your if and else blocks, this will help you see the logic of the code.


I'm not quite sure exactly what your asking or what you mean by "limit" exactly, but I'm guessing (based on how I expect the mod operator to work) that perhaps you're off by one? Perhaps ">=" instead of ">" is what you're looking for?


public void increment()
{
    value++;
    if(value >= limit)
        value = 0;
}


I guess you want

public void increment() 
{
   if(value >= limit)
     value = 0;
   else
     value = value + 1;
}

but it definitely smells like homework...

0

精彩评论

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

关注公众号