Java实现的剪刀石头布游戏示例
程序员文章站
2024-02-11 13:49:16
本文实例讲述了java实现的剪刀石头布游戏。分享给大家供大家参考,具体如下:
choiceanswer.java
public class choiceansw...
本文实例讲述了java实现的剪刀石头布游戏。分享给大家供大家参考,具体如下:
choiceanswer.java
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
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数据结构与算法教程》、《java操作dom节点技巧总结》、《java文件与目录操作技巧汇总》和《java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。