循環的作用是反復執行一段相同或相似的代碼。
循環的三要素:
1)循環變量的初始化
2)循環的條件(以循環變量為基礎)
3)循環變量的改變(向著循環結束的方向改變)
循環變量:在整個循環過程中所反復改變的那個數
循環結構有以下三種
1) while:先判斷后執行,有可能一次也不執行
2)do...while:先執行一次再判斷,滿足條件則繼續執行
循環的三要素中1)和3)相同時,首選do...while
3)for:應用率最高,適用于固定次數循環
另外,break--跳出循環;continue--跳過循環體中剩余語句而進入下一次循環。
案例一:猜數字之while
思路----1)定義一個隨機數 2)接受用戶輸入的數 3)while判斷不等,判斷與隨機數的大小,用戶繼續輸入直到結束循環
int num=(int)(Math.random()*1000+1);
Scanner scan=new Scanner(System.in);
System.out.println("請輸入一個整數(0到1000,輸0退出):");
int guess=scan.nextInt();
while(guess!=num){
? ? ? ? if(guess==0){
? ? ? ? System.out.println("再見!!");
? ? ? ? break;
? ? }
? ? if(guess>num){
? ? ? ? System.out.println("猜大了!");
? ? }else{
? ? ? ? System.out.println("猜小了!");
? ? }
? ? System.out.println("請輸入一個整數(0到1000,輸0退出):");
? ? guess=scan.nextInt();
}
scan.close();
if(guess==num){
? ? System.out.println("恭喜你猜對了!!!");
}
案例一:猜數字之do...while
思路----1)定義一個隨機數 2)do接受用戶輸入的數,判斷與隨機數的大小3)while判斷不等,用戶繼續輸入直到結束循環
int num=(int)(Math.random()*1000+1);
Scanner scan=new Scanner(System.in);
int guess;
do{
? ? System.out.println("請輸入一個整數(0到1000,輸0退出):");
? ? guess=scan.nextInt();
? ? if(guess==0){
? ? ? ? System.out.println("再見!!");
? ? ? ? break;
? ? }
? ? if(guess>num){
? ? ? ? System.out.println("猜大了!");
? ? }else if(guess<num){
? ? ? ? System.out.println("猜小了!");
? ? }
}while(guess!=num);
scan.close();
if(guess==num){
? ? System.out.println("恭喜你猜對了!!!");
}
案例三:隨機加法運算之for
思路----1)出題,定義兩個隨機數 2)答題,接收用戶的輸入3)判題,答對分數累計,答錯不加分
Scanner scan=new Scanner(System.in);
int score=0;
for(int i=1;i<=10;i++){
? ? int a=(int)(Math.random()*100);
? ? int b=(int)(Math.random()*100);
? ? System.out.println("("+i+")"+a+"+"+b+"=?");
? ? System.out.println("請輸入答案(輸入-1可退出):");
? ? int answer=scan.nextInt();
? ? if(answer==-1){
? ? ? ? System.out.println("再見!!");
? ? ? ? break;
? ? }
? ? if(answer==a+b){
? ? ? ? System.out.println("答對了");
? ? ? ? score+=10;
? ? }else{
? ? ? ? System.out.println("答錯了");
? ? }
}
scan.close();
System.out.println("最終得分為:"+score+"分");