今天学习的时while语句,代码如下:
package basic;
/**
* **********************************************
* This is the ninth code. Names and comments are followed original code strictly.
*
* @author WX873
************************************************
*/
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.");
tempSum = 0;
tempValue = 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 whileStatement
现在每天先读一下代码,然后自己尝试全部写出来。读代码的时候在想,第一种方法的条件如果改成tempSum < tempMax,是不是就不用回退。后来测试了一下,不是那样的。最后加上去的数导致tempSum大于tempMax,而跳出循环,而上一次执行了while语句,所以说要得到正确结果,必然要回退到上一步。