黑马程序员技术交流社区

标题: TreeMap模拟石头、剪刀、布游戏 [打印本页]

作者: 曾乐祥    时间: 2016-6-24 11:19
标题: TreeMap模拟石头、剪刀、布游戏
import java.util.Random;
import java.util.Scanner;
import java.util.TreeMap;

/*
// * TreeMap模拟石头剪刀布流戏(1、石头 2、剪刀 3、布)
*/
public class Cycles {

        /**
         * @author zoushibao
         */
        public static void main(String[] args) {
                Scanner sc = new Scanner(System.in);
                while (true) {
                        System.out.println("请开始游戏(1、石头 2、剪刀 3、布),按over结束游戏!");
                        String line = sc.nextLine();
                        if (line.equals("over")) {
                                System.out.println("游戏结束!");
                                break;
                        } else {
                                try {
                                        int guess = Integer.parseInt(line);
                                        if (guess >= 1 && guess <= 3) {
                                                cycels(guess);
                                        }
                                } catch (NumberFormatException e) {
                                }
                        }
                }
        }

        public static void cycels(int guess) {
                TreeMap<Integer, String> tm = new TreeMap<>();
                tm.put(1, "石头");
                tm.put(2, "剪刀");
                tm.put(3, "布");
                Random rd = new Random();
                int computerGuess = rd.nextInt(3) + 1;
                System.out.print("你出的是" + tm.get(guess) + ",");
                System.out.println("电脑出的是" + tm.get(computerGuess) + "。");
                if (guess - computerGuess == -1) {
                        System.out.println("恭喜你赢了!");
                } else if (guess - computerGuess == 1) {
                        System.out.println("抱歉电脑赢了");
                } else if (guess - computerGuess == 0) {
                        System.out.println("你和电脑打平!");
                } else if (guess - computerGuess == 2) {
                        System.out.println("恭喜你赢了!");
                } else {
                        System.out.println("抱歉电脑赢了");
                }
        }
}







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2