Java实现的剪刀石头布游戏示例 您所在的位置:网站首页 java编写石头剪刀布 Java实现的剪刀石头布游戏示例

Java实现的剪刀石头布游戏示例

#Java实现的剪刀石头布游戏示例| 来源: 网络整理| 查看: 265

Java实现的剪刀石头布游戏示例

2021-03-08 13:28xxiaowen JAVA教程

这篇文章主要介绍了Java实现的剪刀石头布游戏,涉及java随机数生成及逻辑判定等相关操作技巧,需要的朋友可以参考下

本文实例讲述了Java实现的剪刀石头布游戏。分享给大家供大家参考,具体如下:

ChoiceAnswer.java

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public class ChoiceAnswer {     String texts[] = { "石头", "剪刀", "布" };     int value; // 【1】石头\t【2】剪刀\t【3】布     String getText() {         return texts[value - 1];     }     ChoiceAnswer(int value) {         this.value = value;     }     /**      * 返回0表示平手,返回1表示赢,返回-1表示输      */     int compTo(ChoiceAnswer c) {         if (value == c.value) {             return 0;         }         if (value + 1 == c.value || (value == 3 && c.value == 1)) {             return 1;         }         return -1;     } }

Game.java

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 import java.util.Scanner; public class Game {     void p(String s) {         System.out.println(s);     }     void showWelcome() {         p("欢迎使用······");         p("请选择:【1】石头\t【2】剪刀\t【3】布");     }     @SuppressWarnings("resource")     ChoiceAnswer getUserChoice() {         Scanner sc = new Scanner(System.in);         int userChoice = Integer.parseInt(sc.nextLine());         while (userChoice < 1 || userChoice > 3) {             p("你输入的不正确!请重新输入!");             userChoice = Integer.parseInt(sc.nextLine());         }         return new ChoiceAnswer(userChoice);     }     ChoiceAnswer getComputerChoice() {         int computerChoice = (int) ((Math.random() * 3) + 1);         return new ChoiceAnswer(computerChoice);     }     void showResult(ChoiceAnswer userChoice, ChoiceAnswer computerChoice) {         int result = userChoice.compTo(computerChoice);         if (result == 0) {             System.out.println("平手,您和电脑均选择了:" + userChoice.getText());         } else if (result == 1) {             System.out.println("恭喜,您赢了!您选择了:" + userChoice.getText()                     + ";   电脑选择了:" + computerChoice.getText());         } else {             System.out.println("对不起,您败了!您选择了:" + userChoice.getText()                     + ";电脑选择了:" + computerChoice.getText());         }     }     void start() {         showWelcome();         ChoiceAnswer userChoice = getUserChoice();         ChoiceAnswer computerChoice = getComputerChoice();         showResult(userChoice, computerChoice);     }     public static void main(String a[]) {         System.out.println("服务器之家测试结果:");         new Game().start();     } }

运行结果:

Java实现的剪刀石头布游戏示例

希望本文所述对大家java程序设计有所帮助。

原文链接:http://blog.csdn.net/wenzhilanyu2012/article/details/8733661



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有