java——while循環經典案例


語句結構:順序,分支,循環

循環:反復運行同一段代碼的語法結構。

正常循環的必要條件:
1、循環體:反復執行的那段代碼。(類似於繞圈長跑)
2、循環變量要有初值。(計數的起點)
3、循環變量要有變化。(計數的結束)

循環三要素:
1、循環體
2、循環變量
3、循環條件

循環的三種實現語句:while、for(foreach)、do-while

一、while循環
語法:
while(循環條件){
循環體;
}

例如:
int x = 1;
if(x<=10){//只判斷一次
System.out.println("繼續");
}

對比:
int x = 1;
while(x<=10){
//反復判斷條件是否成立,成立則執行{循環代碼}
System.out.println("繼續");
}
注意:停不下的循環,叫死循環。(如上)

加上循環變量的變化之后:
int x = 1;
while(x<=10){
System.out.println("繼續");
x++;
}
1)x就是循環變量
2)x<=10循環條件(讓循環繼續執行的條件)
3)x++是循環變量的變化(x起始值和變化量可以根據實際情況變化)

循環的使用場景:
1、循環變量沒有參與到循環體中(如上)
int x = 1;
while(x<=10){
System.out.println("繼續");
x++;
}
2、循環變量參與循環體
例如:
int x = 1;
while(x<=10){
System.out.println("第"+x+"次繼續");//x參與循環體語句
x++;
}

編碼習慣:
1、循環變量一般用i、j、k等等
2、思考循環變量從幾開始,到幾,每次變化多少?

循環變量每次的變化量,成為步長。

問題1:打印100個“我很困”。
public class EX1 {
public static void main(String[] args) {
int i = 1;
while(i<=100){
System.out.println("我很困!");
i++;
}
}
}
問題2:打印1-100之間的所有的整數。
public class EX2 {
public static void main(String[] args) {
int i = 1;
while(i<=100){
System.out.println(i);
i++;
}
}
}
問題3:打印1-100之間的所有的整數和。
public class EX3 {
public static void main(String[] args) {
int i=1;
int sum = 0;
while(i<=100)
{
sum=sum+i;
i++;
}
System.out.println(sum);
}
}
問題4:打印1-100之間的所有偶數。
方法1:
public class EX4 {
public static void main(String[] args) {
int i=1;
while(i<=100){
if(i%20){
System.out.println(i);
}
i++;
}
}
}
方法2:
public class EX5 {
public static void main(String[] args) {
int i=2;
while(i<=100){
System.out.println(i);
i+=2;
}
}
}
問題5:打印1-100之間的所有偶數和。
public class EX6 {
public static void main(String[] args) {
int i=2;
int sum = 0;
while(i<=100){
sum+=i;
i+=2;
}
System.out.println(sum);
}
}
問題6:打印1-100之間3和5的公倍數。
public class EX6 {
public static void main(String[] args) {
int i=1;
while(i<=100){
if(i%3
0&&i%50){
System.out.println(i);
}
i++;
}
}
}
問題7:打印所有的水仙花數。
100-999
public class EX7 {
public static void main(String[] args) {
int i = 100;
while(i<1000)
{
int g = i%10;
int s = i/10%10;
int b = i/100%10;
if(ggg+bbb+sss
i){
System.out.println(i);
}
i++;
}
}
}
問題8:打印2000-2500年之間的所有閏年。
問題9:問題8中每打印4個閏年,換一行。
問題10:打印當前月的日歷。
日 一 二 三 四 五 六
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM