johnnyboyyy
johnnyboyyy

Reputation: 55

Modulo alternatives for Java

I currently have this statement

b = (b + 1) % a.length;

However my prof isn't fond of modulo for this assignment. I was wondering how I would be able to rewrite this to make it work without a modulo..

Any help is appreciated, thank you.

Upvotes: 4

Views: 1392

Answers (2)

Bob Kuhar
Bob Kuhar

Reputation: 11100

If in the context of the question you are trying to make 'b' serve as a index into something of fixed length and you are supposed to increment 'b' until its at the length boundary at which point 'b' gets set back to 0. You Modulo solution is exactly how you see this done "in the real world".

However, in "the real world" telling your prof he is a git rarely works out.

int b = 0;
...
while( !someExitCondition() ) {
  ...
  doSomething( a.get( b ) );
  if ( b + 1 < a.length ) {
    b++;
  } else {
    b = 0;
  }
}

Upvotes: 1

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 235984

Try this, it has the same effect and avoids using modulo. IMHO, the modulo-based solution is preferred, it's a shame that your teacher doesn't like it:

// assuming that `b` is an integer
if (b + 1 >= a.length) {
    b = ((b+1) - ((b+1)/a.length * a.length));
} else {
    b++;
}

Upvotes: 2

Related Questions