0
Java syntax problem - 'for' loop
Here are 2 examples of 'for' loop. Second one fails. Why? // here loop increment part works ok public class testj001 { public static void main(String[] args) { for(int x = 1; x <=5; x+=1, x++) { System.out.println(x); } } } // here it fails. Why? public class testj002 { public static void main(String[] args) { for(int x = 1; x <=5; (x+=1)++) { System.out.println(x); } } }
9 Respuestas
+ 3
@Tilo Klarenbeek actually (x += 1) does return something, that is the new value of x (you could do something like y = (x += 1); and it would work). Still, you can use ++ (and --) only directly in front or after variables, as they not only increase the result by one but also change the value of the variable used.
This also should answer your question, @eMBeer.
+ 2
You can use it to swap the values of two variables in one line like this:
a = a + b - (b = a);
Now a has the value of b and b the value of a.
0
x+=1 equals x=x+1 where x is a variable. It should accept increment operator. x is a result of assignement.
0
just experimenting. of course that x+= 2 solves the problem, but I'm on learning curve :-)
- 1
Should be valid. x+=1 gives back x with changed value only, so it should accept ++ operator.