0.主题
今天主要是熟悉while语句的使用
1.程序及运行结果
代码如下
package basic;
public class WhileStatement {
/**
********************
* The entrance of the program.
*
* @param args Not used now.
********************
*/
public static void main( String args[ ] ) {
whileStatementTest( );
} // Of main
/**
********************
* The sum not exceeding a given value.
********************
*/
public static void whileStatementTest( ) {
int tempMax = 100;
int tempValue = 0;
int tempSum = 0;
// Approach 1.
while( tempSum <= tempMax ) {
tempValue++;
tempSum += tempValue;
System.out.println("tempValue = " + tempValue + ", tempSum = " + tempSum);
} // Of while
tempSum -= tempValue;
System.out.println("The sum not exceeding " + tempMax + " is: " + tempSum);
// Approach 2.
System.out.println("\r\nAlternative approach.");
tempValue = 0;
tempSum = 0;
while( true ) {
tempValue++;
tempSum += tempValue;
System.out.println("tempValue = " + tempValue + ", tempSum = " + tempSum);
if( tempMax < tempSum ) {
break;
} // Of if
} // Of while
tempSum -= tempValue;
System.out.println("The sum not exceeding " + tempMax + " is: " + tempSum);
} // Of whileStatementTest
} // Of class WhileStatement
执行结果如下