因爲採用了隨機數,因此每次編譯結果都不同,結果我就不附圖了。java
public class Elephant { /* * 大象工程 * 1.打開冰箱門 * 2.大象PK * 3.把贏的大象放進冰箱 * 4.關閉冰箱門 * */ public static void main(String[] args) { System.out.println("大象工程啓動:"); //準備兩頭大象,一臺冰箱 String elephantA = "大象A"; String elephantB = "大象B"; //打開冰箱門 System.out.println(" 1.打開冰箱門"); //大象pk //石頭剪刀布,石頭1>剪刀2>布3>石頭1,用數字代替字符 //採用Math函數的Math.random()產生3之內的隨機數,(int)(Math.random()*3+1) System.out.println(" 2.大象pk"); //採用do.while循環,當出現平局時能夠繼續pk String winElephant = null; int i = 0; do { i++; int elephantNumA = (int) (Math.random() * 3 + 1); int elephantNumB = (int) (Math.random() * 3 + 1); //pk開始 //採用switch將數字和字符對應起來 String elephantNameA = null; String elephantNameB = null; switch (elephantNumA) { case 1: elephantNameA = "石頭"; break; case 2: elephantNameA = "剪刀"; break; case 3: elephantNameA = "布"; break; default: System.out.println("錯誤!"); break; } switch (elephantNumB) { case 1: elephantNameB = "石頭"; break; case 2: elephantNameB = "剪刀"; break; case 3: elephantNameB = "布"; break; default: System.out.println("錯誤!"); break; } System.out.println(" "+"第"+i+"場"+" "+elephantA+"-"+elephantNameA+" PK "+elephantB+"-"+elephantNameB); //三種狀況:A贏,B贏,平局 if (elephantNumA == 1 & elephantNumB == 2 || elephantNumA == 2 & elephantNumB == 3 || elephantNumA == 3 & elephantNumB == 1) { System.out.println(" "+elephantA + "贏了"); winElephant = elephantA; } else if (elephantNumA == elephantNumB) { System.out.println(" "+"平局"); } else { System.out.println(" "+elephantB + "贏了"); winElephant = elephantB; } } while (winElephant == null); //勝利的進入冰箱 System.out.println(" 3.把"+winElephant+"放進冰箱"); //關閉冰箱門,結束 System.out.println(" 4.關閉冰箱門"); System.out.println("大象工程結束!"); } }