回圈有三種方式:while、do while、for, 中斷回圈也有三種方式:continue、break、return, 下面逐一解釋:
while回圈:
語法結構:
while(回圈條件){
回圈體;
}
回圈條件:可以是一個布爾型別的運算式,也可以是布爾型別的值
特點:不限次數的回圈,滿足某一條件的時候,跳出回圈,
while回圈嵌套:
while(){//外回圈
while(){
//內回圈}
}
//列印一個五行十列的格子
int row = 0;
while (row < 5 ){
row++;
int col = 0;
System.out.println();
while(col < 10){
col++;
System.out.print("*");
}
}
運行結果:
**********
**********
**********
**********
**********
do while回圈
語法結構:
do{
回圈體;
}while(回圈條件);
特點:先執行一次,然后再進行判斷是否滿足回圈,
關于 while 和 do while 有個段子:
while:你要不要?不要,那就不do, do while:先爽一次再問,還要不要?不要,結束回圈,
for回圈
語法結構:
for(回圈變數;回圈條件;回圈變數變化方式){
回圈體;
}
ex: 1 2 3
for(int a = 0;a < 10;a ++){
回圈體; 4
}
//執行順序:1243
//列印五行十列的空心矩形
public class HollowRectangle {
public static void main(String[] args) {
for(int i = 1;i <= 5;i ++){
for(int j = 1;j <= 10;j ++){
if(i == 1 ||i == 5)
System.out.print("*");
else if(j == 1 || j == 10 )
System.out.print("*");
else System.out.print(" ");
}
System.out.println();
}
}
}
運行結果:
**********
* *
* *
* *
**********
break
跳出當前回圈,
public static void main(String[] args) {
int i = 0;
System.out.println("干飯啦!");
while(i<6){
i++;
if(i == 3){
break;
}
System.out.println("這是第"+i+"碗飯");
}
}
運行結果:
干飯啦!
這是第1碗飯
這是第2碗飯
continue
終止本次回圈,進入下次回圈,
public static void main(String[] args) {
int i = 0;
System.out.println("干飯啦!");
while(i<6){
i++;
if(i == 3){
continue;
}
System.out.println("這是第"+i+"碗飯");
}
}
運行結果:
干飯啦!
這是第1碗飯
這是第2碗飯
這是第4碗飯
這是第5碗飯
這是第6碗飯
return
直接結束所有回圈(結束當前回圈所在的方法,return后面的內容,都不再執行)
return一出,直接毀天滅地,
public static void main(String[] args) {
int i = 0;
while(i<6){
i++;
System.out.println("干飯啦!");
return;
}
}
運行結果:
干飯啦!
綜合實戰:猜數字游戲
import java.util.Random;
public class GuessGame {
public static void main(String[] args) {
Random random = new Random();
int num = random.nextInt(100) + 1;
//生成亂數(1-100)
System.out.println("請輸入一個整數(1-100):");
Scanner scanner = new Scanner(System.in);
int count = 0;
while(true){
count++;
int console;
console = scanner.nextInt();
if(console < num){
System.out.println("你輸入的數太小了!再來試試:");
}else if(console >num){
System.out.println("你輸入的數太大了!再來試試:");
}else{
System.out.println("恭喜你猜對了,猜測次數為:"+count);
if(count < 3){
System.out.println("你是個天才!");
}else if(count < 6){
System.out.println("你是個人才!");
}else{
System.out.println("你媽媽喊你回家吃飯了!");
}
break;
}
}
}
}
運行結果:
請輸入一個整數(1-100):
50
你輸入的數太小了!再來試試:
75
你輸入的數太小了!再來試試:
87
你輸入的數太小了!再來試試:
94
你輸入的數太大了!再來試試:
90
恭喜你猜對了,猜測次數為:5
你是個人才!
個人學習筆記,若有誤還望不吝賜教,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/206311.html
標籤:其他
