while循环
代码展示
总结
while循环
while(判断条件){undefined
循环体
}
Java提供了三种类型的循环语句:while循环,do-while循环和for循环。
while循环在每次循环开始前,先会判断条件是否成立。如果计算结果为true,就把循环体内的语句执行一遍,如果计算结果为false,那就直接跳到while循环的末尾,继续往下执行。
举个例子
public class Main {
public static void main(String[] args) {
int sum = 0; // 累加的和,初始化为0
int n = 1;
while (n <= 100) { // 循环条件是n <= 100
sum = sum + n; // 把n累加到sum中
n ++; // n自身加1
}
System.out.println(sum); // 5050
}
}
在while循环中可以使用break关键字,跳出该循环。
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
代码展示
package basic;
/**
*
*
* @author Donghao Xu
*/
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
while(true)可作为无限循环,可以由自己循环中的某个条件式来结束。
while(true) {
语句;
if(条件式)
break; // 跳离当前循环
...
}
区分break和continue
1.break
有时候我们想在某种条件出现的时候终止循环而不是等到循环条件为false才终止。
这是我们可以使用break来完成。break用于完全结束一个循环,跳出循环体执行循环后面的语句。
2.continue
continue和break有点类似,区别在于continue只是终止本次循环,接着还执行后面的循环,break则完全终止循环。
可以理解为continue是跳过当次循环中剩下的语句,执行下一次循环。
总结
通过矩阵加法和乘法,把for循环和while循环再次进行回顾。