您好,登錄后才能下訂單哦!
本文實(shí)例講述了Java實(shí)現(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("請(qǐng)選擇:【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("你輸入的不正確!請(qǐng)重新輸入!"); 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("對(duì)不起,您敗了!您選擇了:" + 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("億速云測(cè)試結(jié)果:"); new Game().start(); } }
運(yùn)行結(jié)果:
更多關(guān)于java算法相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。