iT邦幫忙

2022 iThome 鐵人賽

DAY 5
0

想必學程式語言都會遇到的課題...就是loop

其實能用for loop寫也能用while loop寫

來個經典「猜密碼」案例說明
● while loop 版本

import java.util.Random;
import java.util.Scanner;

public class GuessNumber {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int min = 0;
        int max = 100;
        Random r = new Random();
        int secret = r.nextInt(max - min) + min;
        
        while (true) {
            System.out.print("Make a guess (between " + min + " and " + max + "): ");
            int guess = s.nextInt();

            if (guess < min || guess > max) {
                System.out.println("Plaese make a valid guess.");
                continue;
            }

            if (guess == secret) {
                System.out.println("You win!! The secret is " + secret);
                break;
            } else {
                if (guess > secret) {
                    max = guess;
                } else {
                    min = guess;
                }
            }
        }
    }
}

● for loop 版本

import java.util.Random;
import java.util.Scanner;

public class GuessNumber {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int min = 0;
        int max = 100;
        Random r = new Random();
        int secret = r.nextInt(max - min) + min;

        // i為計數器
        for (int i = 0; i != secret; ) {
            System.out.print("Make a guess (between " + min + " and " + max + "): ");
            int guess = s.nextInt();
            if (guess < min || guess > max) {
                System.out.println("Plaese make a valid guess.");
                continue;
            }
            if (guess == secret) {
                System.out.println("You win!! The secret is " + secret);
                break;
            } else {
                if (guess > secret) {
                    max = guess;
                } else {
                    min = guess;
                }
            }
        }
    }
}

以上兩個版本的程式碼幾乎一模一樣,但就此案例使用for loop的Space Complexity就為較差

多出了一個int i; 要去做計數,但計數器i 卻無關程式執行結果

綜上,總結一下for loop & while loop 分別使用時機:

  • for loop:當已知loop執行次數,可用計數器去控制迴圈的終止
  • while loop:當未知loop執行次數,需用條件(一般是boolean)去終止迴圈

希望藉由以上說明能對初接觸寫程式的新手有所幫助:)


上一篇
簡單聊聊TPS(Toyota Production System)
下一篇
SQL | NoSQL
系列文
寫寫歷年職場經歷過的大小事或近期所學習的知識啟發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言