ackage com.itheima_05;
/*
* while循環(huán)語句的基本格式:
* while(判斷條件語句) {
* 循環(huán)體語句;
* }
* 擴展格式:
* 初始化語句;
* while(判斷條件語句) {
* 循環(huán)體語句;
* 控制條件語句;
* }
*
* 回顧for循環(huán)的語句格式:
* for(初始化語句;判斷條件語句;控制條件語句) {
* 循環(huán)體語句;
* }
*/
public class WhileDemo {
public static void main(String[] args) {
//輸出10次HelloWorld
/*
for(int x=1; x<=10; x++) {
System.out.println("HellloWorld");
}
*/
//while循環(huán)實現(xiàn)
int x=1;
while(x<=10) {
System.out.println("HellloWorld");
x++;
}
}
}
package com.itheima_05;
/*
* 求1-100之和。
* 練習(xí):統(tǒng)計水仙花個數(shù)。
*/
public class WhileTest {
public static void main(String[] args) {
//回顧for循環(huán)實現(xiàn)
/*
//定義求和變量
int sum = 0;
//獲取1-100之間的數(shù)據(jù)
for(int x=1; x<=100; x++) {
//累加
sum += x;
}
System.out.println("1-100的和是:"+sum);
*/
//while循環(huán)實現(xiàn)
//定義求和變量
int sum = 0;
int x = 1;
while(x<=100) {
sum += x;
x++;
}
System.out.println("1-100的和是:"+sum);
}
}