Can someone explain to me why i can write "i+2" as a post-condition while iterating through a List<> in a for-each loop, but have to write "i=i+2" while iterating through an Array?
for(int i = 0; i < numbers.length; i+2)
{
numbers[i] = 2;
System.out.println(numbers[i]);
}
The ForUpdate
has to be a StatementExpressionList
, ie a list of StatementExpression
s.
i+2
is an expression, but not a statement expression.
Statement expressions can be informally (*) thought of as expressions which might have a side effect, and thus it makes sense for them to stand alone in a statement by themselves. i+2
doesn't have a side effect, so there is no point in evaluating it.
(*) Informally, because method1() + method2()
can have a side effect, because methodN()
can have a side effect; and yet, it is not a statement expression because the "main" expression here - the addition - has no side effect in and of itself.
You could write this as for (;; method1(), method2()) { ... }
(with no addition) if this was what you wanted in your ForUpdate
.
i+2 it's an expression, you have to assign a result to somewhere, so the correct syntax is:
for(int i = 0; i < numbers.length; i=i+2)
{
numbers[i] = 2;
System.out.println(numbers[i]);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.