Java實現(xiàn)的剪刀石頭布游戲示例
本文實例講述了Java實現(xiàn)的剪刀石頭布游戲。分享給大家供大家參考,具體如下:
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("腳本之家測試結(jié)果:");
new Game().start();
}
}
運行結(jié)果:

更多關于java算法相關內(nèi)容感興趣的讀者可查看本站專題:《Java數(shù)據(jù)結(jié)構與算法教程》、《Java操作DOM節(jié)點技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設計有所幫助。
相關文章
springboot整合Excel填充數(shù)據(jù)代碼示例
這篇文章主要給大家介紹了關于springboot整合Excel填充數(shù)據(jù)的相關資料,文中通過代碼示例介紹的非常詳細,對大家學習或者使用springboot具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08
Java基于Calendar類輸出指定年份和月份的日歷代碼實例
這篇文章主要介紹了Java 使用Calendar類輸出指定年份和月份的日歷,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-02-02
Java數(shù)據(jù)結(jié)構之數(shù)組(動力節(jié)點之Java學院整理)
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構之數(shù)組(動力節(jié)點之Java學院整理)的相關資料,包括創(chuàng)建和內(nèi)存分配,數(shù)組封裝后的使用等,需要的朋友參考下吧2017-04-04
深入淺析Java中普通代碼塊、構造代碼塊與靜態(tài)代碼塊
這篇文章主要介紹了Java中普通代碼塊、構造代碼塊與靜態(tài)代碼塊的相關資料,靜態(tài)代碼塊>Main()>構造代碼塊 。非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-08-08
JavaWeb項目實現(xiàn)文件上傳動態(tài)顯示進度實例
本篇文章主要介紹了JavaWeb項目實現(xiàn)文件上傳動態(tài)顯示進度實例,具有一定的參考價值,有興趣的可以了解一下。2017-04-04
spring-boot.version2.6升級到2.7.18后security報錯問題
這篇文章主要介紹了spring-boot.version2.6升級到2.7.18后security報錯問題及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08

