Reputation: 13
Basically in the following method I'm trying to say: If z2 does not equal 0, z2 - 1. else add 6 to z2. I know it's probably stupid but I'm quite new to programming. The code as follows:
int z2 = someValue;
if(z2 != 0){
z2--;
}
else{
z2 + 6;
}
Thanks
Upvotes: 1
Views: 45
Reputation: 109597
The math operation for that is modulo, in java the operator %
, remainder of division.
| x | x % 3 |
|-----|-------|
| 6 | 0 |
| 5 | 2 |
| 4 | 1 |
| 3 | 0 |
| 2 | 2 |
| 1 | 1 |
| 0 | 0 |
| -1 | -1 |
| -2 | -2 |
| -3 | 0 |
| -4 | -1 |
Using integer division /
(5/3 == 1):
y % x == y - x * (y / x)
Notice the sign when one of the sides is negative.
In your case a decrement becomes:
z2 = (z2 - 1 + 7) % 7;
or short
z2 = (z2 + 6) % 7;
Care has been taken that the left hand side of %
remains positive. The result then is in 0 .. 6
.
For those interested in latin modulus is actually called the operation (a noun), but in an expression gets the adverbal ending
o
(ablativus): "34 modulo 7 is 6". But modulo will do fine used as noun.
Upvotes: 0
Reputation: 521997
You need to assign z2
to a value in the else
condition:
if (z2 != 0) {
z2--; // same as z2 = z2 - 1
}
else {
z2 += 6; // same as z2 = z2 + 6
}
But we could do this with a single line of code, using a ternary expression:
z2 = z2 != 0 ? z2 - 1 : z2 + 6;
Upvotes: 1