Day09 —— While 循环
1. Background
今天是学习java的第9天了,今天学习的内容是while循环。
在我的心里面while循环是比for循环更加简单的存在,一直是把它当作for的下位替代来的。记得我三年前刚学C语言的时候,就只会一个while循环,然后用while循环实现了冒泡排序等等简单排序。可是之后学完for循环之后,写程序几乎没有用过while了,因为for属实好用。
2. Description
今天的代码是用while循环求和,但是Sum不能超过一个最大值,其中求和的value每次自增1.
代码比较简单,整体和C语言相似,所以就直接上代码了。
3.Code
package basic;
/**
* This is the ninth code.
*
* @author Leo liu lyx1443807042@163.com.
*/
public class Day09 {
/**
*******************
* 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 tempValue = 0;
int tempSum = 0;
int tempMax = 100;
// Approach 1.
while (tempSum <= tempMax) {
tempValue++;
tempSum += tempValue;
System.out.println("tempvalue = " + tempValue + " , tempSum = " + tempSum);
} // Of while
tempSum -= tempValue; // 当tempSum大于tempMax时才会跳出循环,与所求不符,故减去最后的加的那个tempValue.
System.out.println("The sum not exceeding " + tempMax +" is: " + tempSum);
// Approach 2.
tempSum = 0;
tempValue = 0; // 此处展示第二种求值方法,为避免上面代码对变量的污染,此处重新初始化变量
while (true) {
if (tempSum > tempMax) {
break;
} // Of if
tempValue++;
tempSum += tempValue;
System.err.println("tempvalue = " + tempValue + " , tempSum = " + tempSum);
} // Of while
tempSum -= tempValue;
System.out.println("The sum not exceeding " + tempMax +" is: " + tempSum);
} // Of whileStatementTest
} // Of Day09
运行结果: