Untitled
unknown
plain_text
a year ago
2.7 kB
9
Indexable
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
// Method to get the computer's choice
public static String getComputerChoice(String[] choices) {
Random rand = new Random();
int index = rand.nextInt(choices.length); // Randomly select one of the choices
return choices[index];
}
// Method to determine the winner based on player's choice and computer's choice
public static String determineWinner(String playerChoice, String computerChoice) {
if (playerChoice.equals(computerChoice)) {
return "It's a tie!";
} else if ((playerChoice.equals("rock") && computerChoice.equals("scissors")) ||
(playerChoice.equals("scissors") && computerChoice.equals("paper")) ||
(playerChoice.equals("paper") && computerChoice.equals("rock"))) {
return "You win!";
} else {
return "Computer wins!";
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] choices = {"rock", "paper", "scissors"}; // Array of possible choices
System.out.println("Welcome to Rock, Paper, Scissors!");
// Loop to allow multiple rounds
boolean keepPlaying = true;
while (keepPlaying) {
System.out.print("Enter rock, paper, or scissors (or 'exit' to quit): ");
String playerChoice = scanner.nextLine().toLowerCase();
// Allow player to quit the game
if (playerChoice.equals("exit")) {
keepPlaying = false;
System.out.println("Thanks for playing!");
break;
}
// Check if player input is valid
boolean validChoice = false;
for (String choice : choices) {
if (playerChoice.equals(choice)) {
validChoice = true;
break;
}
}
if (!validChoice) {
System.out.println("Invalid choice, please try again.");
continue;
}
// Get the computer's choice
String computerChoice = getComputerChoice(choices);
System.out.println("Computer chose: " + computerChoice);
// Determine and display the winner
String result = determineWinner(playerChoice, computerChoice);
System.out.println(result);
System.out.println();
}
scanner.close(); // Close the scanner to avoid resource leaks
}
}Editor is loading...
Leave a Comment