for Statement
ForStatement:
1)BasicForStatement
2)EnhancedForStatement
The for statement has two forms:
• The basic for statement.
• The enhanced for statement
The basic for Statement
The basic for statement executes some initialization code, then executes an
Expression, a Statement, and some update code repeatedly until the value of the
Expression is false.
BasicForStatement:
for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement
ForStatementNoShortIf:
for ( ForInitopt ; Expressionopt ; ForUpdateopt )
StatementNoShortIf
ForInit:
StatementExpressionList
LocalVariableDeclaration
ForUpdate:
StatementExpressionList
StatementExpressionList:
StatementExpression
StatementExpressionList , StatementExpression
The Expression must have type boolean or Boolean, or a compile-time error
occurs.
The following example, which calculates the sum of an integer array, shows how enhanced
for works for arrays:
int sum(int[] a)
{
int sum = 0;
for (int i : a)
sum += i;
return sum;
}
Here is an example that combines the enhanced for statement with auto-unboxing to translate
a histogram into a frequency table:
Map histogram = ...;
double total = 0;
for (int i : histogram.values())
total += i;
for (Map.Entry e : histogram.entrySet())
System.out.println(e.getKey() + "" + e.getValue() / total);
ForStatement:
1)BasicForStatement
2)EnhancedForStatement
The for statement has two forms:
• The basic for statement.
• The enhanced for statement
The basic for Statement
The basic for statement executes some initialization code, then executes an
Expression, a Statement, and some update code repeatedly until the value of the
Expression is false.
BasicForStatement:
for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement
ForStatementNoShortIf:
for ( ForInitopt ; Expressionopt ; ForUpdateopt )
StatementNoShortIf
ForInit:
StatementExpressionList
LocalVariableDeclaration
ForUpdate:
StatementExpressionList
StatementExpressionList:
StatementExpression
StatementExpressionList , StatementExpression
The Expression must have type boolean or Boolean, or a compile-time error
occurs.
The following example, which calculates the sum of an integer array, shows how enhanced
for works for arrays:
int sum(int[] a)
{
int sum = 0;
for (int i : a)
sum += i;
return sum;
}
Here is an example that combines the enhanced for statement with auto-unboxing to translate
a histogram into a frequency table:
Map
double total = 0;
for (int i : histogram.values())
total += i;
for (Map.Entry
System.out.println(e.getKey() + "" + e.getValue() / total);
0 comments:
Post a Comment