今天練習了一下亂數程式撰寫
package com.java.random;
import java.util.*;
public class Guess {
public static void main(String[] arg) {
Scanner scanner = new Scanner(System.in);
int number = (int) (Math.random() * 10);
int guess;
do {
System.out.println("你看不見我,實際數字:" + number);
System.out.println("輸入");
guess = scanner.nextInt();
} while (guess != number);
System.out.println("猜中");
}
}
因為我比較懶惰,所以又寫了另外一隻,讓系統自己玩。
package com.java.random;
import java.util.*;
public class RandomSample {
public static void main(String[] arg) {
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入系統比對次數");
int max = scanner.nextInt();
for (int i = 0; i < max; i++) {
// 產生0 ~ 42正整數
int random1 = (int) (Math.random() * 42 + 1);
int random2 = (int) (Math.random() * 42 + 1);
if (random1 == random2) {
System.out.println("於第" + i + "次命中");
break;
} else {
System.out.println("運氣很差~~~");
}
}
}
}
感覺下面比較像一點
package com.java.random;
import java.util.*;
public class RandomSample {
public static void main(String[] arg) {
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入系統比對次數");
int max = scanner.nextInt();
// 產生0 ~ 42正整數
int random1 = (int) (Math.random() * 42 + 1);
System.out.println("系統產生亂數:" + random1);
for (int i = 0; i < max; i++) {
int random2 = (int) (Math.random() * 42 + 1);
System.out.println("電腦A:猜測亂數" + random2);
if (random1 == random2) {
System.out.println("電腦A於第" + i + "次命中");
break;
} else {
System.out.println("下次再來~~~");
}
}
}
}
沒有留言:
張貼留言