This is the kind of thing you need to do with some frequency, especially within loops. Java makes incrementing and decrementing a variable by 1 easy with these special operators:
x = 0; x++; //x is 1
You can subtract the same way:
y = 10; y--;
The preceding operators are called post-increment and post-decrement, because they add or subtract 1 after the variable has been evaluated.
|
You can also use these operators for pre-incrementing and pre-decrementing, which adds or subtracts 1 before the variable has been evaluated. Like this:
--x; ++y;
Here is a class you can compile and run to demonstrate these operators:
public class OperatorTest { public static void main(String[] args) { int x = 10; //evaluate, then increment System.out.println("post decrement: " + x++); //prints 10 System.out.println(x); //x is now 11 //decrement, then evaluate System.out.println("pre decrement : " + —x); //prints 10 } }
3.149.243.32