1 import java.util.Scanner; 2 3 import java.util.Random; 4 5 public class TestGuess{ 6 7 public static void main(String[] args){ 8 9 Scanner yc = new Scanner(System.in); 10 Random cy = new Random(); 11 12 System.out.println("=============================================="); 13 System.out.println("====================人機猜拳=================="); 14 System.out.println("=============================================="); 15 System.out.println("====數字1 = 剪刀 數字2 = 石頭 數字3 = 布===="); 16 System.out.println("=============================================="); 17 18 int computerCount = 0; //電腦的獲勝次數 19 int playerCount = 0; //玩家的獲勝次數 20 21 for(int i = 1;i <= 3;){ 22 23 int computer = cy.nextInt(3) + 1; //表示隨機獲得0、1、2;追加1后,變為1、2、3 24 25 System.out.println("請玩家輸入對應的數字:"); 26 int player = yc.nextInt(); 27 28 //比較猜拳 29 if(computer == player){ //平局 30 31 System.out.println("平局,再接再厲!"); 32 continue; //不加 33 34 }else if((player == 1 && computer == 3)||(player == 2 && computer == 1)||(player == 3 && computer == 2)){ 35 36 System.out.println("恭喜,您贏得了對局!"); 37 playerCount++; //玩家勝率+1 38 39 }else{ 40 41 System.out.println("很遺憾,您未贏得對局!"); 42 } 43 44 //判斷雙方是否已經存在其中一方連勝兩局的情況 45 if(playerCount == 2||computerCount == 2){ 46 break; 47 } 48 49 i++; 50 } 51 52 if(playerCount == 2){ 53 54 System.out.println("游戲結束,玩家獲勝!"); 55 56 }else{ 57 58 System.out.println("游戲結束,電腦獲勝!"); 59 } 60 61 } 62 }
*如有不足 還請多多指點!