---
# System prepended metadata

title: Java自學紀錄 - 猜拳遊戲
tags: [Java]

---

###### tags: `Java`
# Java自學紀錄 - 猜拳遊戲
## 學習重點
* 決策敘述
* switch來判斷事件
* 亂數來控制電腦出拳
### switch運用
```java=
switch([運算式]):{
    case [常數1]:
        [敘述區塊1];
        [break]; //跳出這個case
    case [常數2]:
        [敘述區塊2];
        [break];
}
```
### 亂數運用
```java=
宣告 n;
([型態])(Math.random()*n);

//example
//要做出一個0~10的亂數

int n=10;
(int)(Math.random()*10);
```
# 猜拳實作

``code``
```java=
import java.util.Scanner;

public class Java猜拳遊戲 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String fa="",fb="",result="";
        int a,b;
        a = in.nextInt(); //player's punch
        b = (int)Math.floor(Math.random()*3); //create 0~2 random
        System.out.println("Input 0 is paper, 1 is scissors, 2 is stone");
        switch (a){
            case 0:
                fa = "paper";
                switch (b){
                    case 0:
                        fb = "paper";
                        result = "Tie";
                        break;
                    case 1:
                        fb = "scissors";
                        result = "Computer win";
                        break;
                    case 2:
                        fb = "stone";
                        result = "You win";
                        break;
                }
                break;
            case 1:
                fa = "scissors";
                switch (b){
                    case 0:
                        fb = "paper";
                        result = "You win";
                        break;
                    case 1:
                        fb = "scissors";
                        result = "Tie";
                        break;
                    case 2:
                        fb = "stone";
                        result = "Computer win";
                        break;
                }
                break;
            case 2:
                fa = "stone";
                switch (b) {
                    case 0:
                        fb = "paper";
                        result = "Computer win";
                        break;
                    case 1:
                        fb = "scissors";
                        result = "You win";
                        break;
                    case 2:
                        fb = "stone";
                        result = "Tie";
                        break;
                }
                break;
        }
        System.out.println("Your punch is : " + fa);
        System.out.println("Computer's punch is : " + fb);
        System.out.println("This game's result is : " + result);
    }
}
```
>下圖為執行結果
>
![](https://i.imgur.com/Ba6gaA6.png)


