本文實例講述了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程序設計有所幫助。
原文鏈接:http://blog.csdn.net/wenzhilanyu2012/article/details/8733661