本文實(shí)例講述了Java實(shí)現(xiàn)的剪刀石頭布游戲。分享給大家供大家參考,具體如下:
北海網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)!從網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、自適應(yīng)網(wǎng)站建設(shè)等網(wǎng)站項(xiàng)目制作,到程序開發(fā),運(yùn)營(yíng)維護(hù)。創(chuàng)新互聯(lián)成立于2013年到現(xiàn)在10年的時(shí)間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來(lái)保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(liá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("創(chuàng)新互聯(lián)測(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ì)有所幫助。
網(wǎng)站名稱:Java實(shí)現(xiàn)的剪刀石頭布游戲示例
當(dāng)前地址:http://chinadenli.net/article36/jgggpg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號(hào)、電子商務(wù)、、服務(wù)器托管、企業(yè)網(wǎng)站制作、響應(yīng)式網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)