while以及break的用法:
此代码段运用了两种while的用法,一种是while里面写循环条件,看是否继续执行循环,第二种是条件为true,即无限循环,但是通过break+if判断条件,使其退出循环
此处的break与switch中的break作用相同
代码:
package yrx;
public class WhileStatemen {
public static void main(String arg[]) {
whileStatementTest();
}// of main
/**
*********************
* The sum not exceeding a given value.
*********************
*/
public static void whileStatementTest() {
int tempMax = 100;
int tempValue = 0;
int tempSum = 0;
// Approach1
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);
// Approach2
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 it
} // of while
tempSum -= tempValue;
System.out.println("The sum not exceeding " + tempMax + "is:" + tempSum);
}// of whileStatementTest
}// of class WhileStatement
运行结果: