难点:理解最后一次循环,注意减去最后一次循环加上的值。在判断所求最后一次和的大小时,求和函数没有停止,所以最后的输出要减去最后一个值。
package day9;
public class WhileStatement {
/**
*********************
* 程序开始.
*
* @param args
* Not used now.
*********************
*/
public static void main(String args[]) {
whileStatementTest();
}// Of main
/**
*********************
* 不超过给定值的总和.
*********************
*/
public static void whileStatementTest() {
int tempMax = 100;
int tempValue = 0;
int tempSum = 0;
// Approach 1.(判断求和值是否小于等于100)
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.(当求和值大于100时终止)
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
注意:while语句的判断要注意最后的判断,多练习,不然很容易出错。