想必學程式語言都會遇到的課題...就是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 分別使用時機:
希望藉由以上說明能對初接觸寫程式的新手有所幫助:)