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); } } }

31st Jan 2017, 11:17 PM
eMBeer
9 Antworten
+ 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.
31st Jan 2017, 11:52 PM
Robobrine
Robobrine - avatar
+ 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.
1st Feb 2017, 12:04 AM
Robobrine
Robobrine - avatar
0
x+=1 equals x=x+1 where x is a variable. It should accept increment operator. x is a result of assignement.
31st Jan 2017, 11:30 PM
eMBeer
0
just experimenting. of course that x+= 2 solves the problem, but I'm on learning curve :-)
31st Jan 2017, 11:44 PM
eMBeer
- 1
Should be valid. x+=1 gives back x with changed value only, so it should accept ++ operator.
31st Jan 2017, 11:24 PM
eMBeer