在貼吧看到的題目,放假有空做一做
import java.util.Scanner;
class RockPaperScissors {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
RPSUtil rpsu = new RPSUtil();
boolean run = true;
System.out.println("Rock-Paper-Scissors game:");
System.out.println("Welcome to this game.");
try {
while (run) {
System.out.println("How many times do you want to play?");
int times = sc.nextInt();
System.out.println("Game start");
String result = rpsu.turn(times);
System.out.println(result);
System.out.println("Do you want to play again(Y/N)");
sc = new Scanner(System.in);
String flag = sc.nextLine();
if (flag.equals("Y")) {
} else if (flag.equals("N")) {
run = false;
} else {
System.out.println("Please input Y or N");
}
}
} catch (Exception e) {
}
}
}
class RPSUtil {
public String turn(int times) {
Scanner sc = new Scanner(System.in);
int winCounter = 0;
int drawCounter = 0;
int computerChoice = 0;
String choice;
int result = 0;
for (int i = 0; i < times; i++) {
System.out.println("Turn " + (i + 1));
System.out.println("rock-paper-scissors (A,B,C)?");
// rock(石)-paper(布)-scissors(剪刀)
choice = sc.nextLine();
// A->0,B->1,C->2
//getting random number for computer choice
computerChoice = (int) (Math.random() * 3 + 1);
if (choice.equals("A")) {
System.out.println("Your choice is rock");
result = compareChoice(0, computerChoice);
printComputerChoice(computerChoice);
} else if (choice.equals("B")) {
System.out.println("Your choice is paper");
result = compareChoice(1, computerChoice);
printComputerChoice(computerChoice);
} else if (choice.equals("C")) {
System.out.println("Your choice is scissors");
result = compareChoice(2, computerChoice);
printComputerChoice(computerChoice);
}
if (result == 1) {
System.out.println("You Win");
winCounter++;
} else if (result == 0) {
System.out.println("Draw game");
drawCounter++;
} else {
System.out.println("You lose");
}
}
return "You totally play " + times + " times " + "\nWin : "
+ winCounter + "\nDraw : " + drawCounter + "\nLose : "
+ (times - winCounter - drawCounter)
+ "\nYour winning percentage is : "
+ (int) ((winCounter / (double) (times)) * 100);
}
public int compareChoice(int choice, int computerChoice) {
// 0是平局,1是勝,-1是負
if (choice == computerChoice)
return 0;
if (choice == 0) {
if (computerChoice == 2)
return 1;
else
return -1;
} else if (choice == 1) {
if (computerChoice == 0)
return 1;
else
return -1;
} else {
if (computerChoice == 1)
return 1;
else
return -1;
}
}
public void printComputerChoice(int computerChoice) {
String msg = "Computer's choice is ";
if (computerChoice == 0)
System.out.println(msg + "rock");
else if (computerChoice == 1)
System.out.println(msg + "paper");
else
System.out.println(msg + "scissors");
}
}