「Java学习打卡」45、面向对象题目练习

编程模拟剪刀、石头和布游戏。游戏规则为:剪刀剪纸,石头砸剪刀,布包石头。玩游戏者从键盘输入s(表示剪刀)或r(表示石头)或p(表示布),要求两个游戏者交替输入,计算机给出输赢的信息。

import java.util.Scanner;

class Dice {
     
    private int m;
    private int r;
    public Dice(String d, String n) {
     

        switch (d) {
     
            case "r":
                System.out.println("你出的是石头");
                this.m = 1;
                break;
            case "s":
                System.out.println("你出的是剪刀");
                this.m = 2;
                break;
            case "p":
                System.out.println("你出的是布");
                this.m = 3;
                break;
            default:
                System.out.println("你输入的不正确");
                return;
        }
        switch (n) {
     
            case "r":
                System.out.println("我出的是石头");
                this.r = 1;
                break;
            case "s":
                System.out.println("我出的是剪刀");
                this.r = 2;
                break;
            case "p":
                System.out.println("我出的是布");
                this.r = 3;
                break;
            default:
                System.out.println("我输入的不正确");
                return;
        }
        roll(m, r);
    }

    public int roll(int d, int n) {
     
        if (d == n) System.out.println("平手");
        else if (d - n == 1) System.out.println("你赢了");
        else if (d == 1 && n == 3) System.out.println("你赢了");
        else System.out.println("你输了");
        return 0;
    }
}

public class Test {
     
    public static void main(String[] args) {
     
        System.out.println("r代表石头:s代表剪刀:p代表布:");
        System.out.println("请出拳");
        Scanner scan0 = new Scanner(System.in);
        String str0 = scan0.nextLine();
        System.out.println("请对方出拳");
        Scanner scan1 = new Scanner(System.in);
        String str1 = scan1.nextLine();
        Dice d = new Dice(str0, str1);
    }
}

你可能感兴趣的:(「Java学习打卡」45、面向对象题目练习)