Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- import java.util.Scanner;
- public class RockPaperScissors {
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- Random random = new Random();
- boolean playAgain = true;
- while (playAgain) {
- int computerChoice = random.nextInt(3) + 1; //1=rock, 2=paper, 3=scissors
- System.out.println("Let's play Rock, Paper, Scissors!");
- System.out.print("Enter your choice (1=rock, 2=paper, 3=scissors): ");
- int userChoice = input.nextInt();
- System.out.println("You chose " + getChoice(userChoice));
- System.out.println("The computer chose " + getChoice(computerChoice));
- int result = getResult(userChoice, computerChoice);
- if (result == 0) {
- System.out.println("It's a tie!");
- } else if (result == 1) {
- System.out.println("You win!");
- } else {
- System.out.println("The computer wins!");
- }
- System.out.print("Do you want to play again? (y/n): ");
- String playAgainChoice = input.next();
- if (!playAgainChoice.equalsIgnoreCase("y")) {
- playAgain = false;
- }
- }
- }
- public static String getChoice(int choice) {
- switch (choice) {
- case 1:
- return "rock";
- case 2:
- return "paper";
- case 3:
- return "scissors";
- default:
- return "invalid";
- }
- }
- public static int getResult(int userChoice, int computerChoice) {
- if (userChoice == computerChoice) {
- return 0;
- } else if ((userChoice == 1 && computerChoice == 3) || (userChoice == 2 && computerChoice == 1) || (userChoice == 3 && computerChoice == 2)) {
- return 1;
- } else {
- return -1;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement