Advertisement
MrBooshot712

rpsjava

May 8th, 2023
638
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.97 KB | Source Code | 0 0
  1. import java.util.Random;
  2. import java.util.Scanner;
  3.  
  4. public class RockPaperScissors {
  5.     public static void main(String[] args) {
  6.         Scanner input = new Scanner(System.in);
  7.         Random random = new Random();
  8.  
  9.         boolean playAgain = true;
  10.         while (playAgain) {
  11.             int computerChoice = random.nextInt(3) + 1; //1=rock, 2=paper, 3=scissors
  12.  
  13.             System.out.println("Let's play Rock, Paper, Scissors!");
  14.             System.out.print("Enter your choice (1=rock, 2=paper, 3=scissors): ");
  15.             int userChoice = input.nextInt();
  16.  
  17.             System.out.println("You chose " + getChoice(userChoice));
  18.             System.out.println("The computer chose " + getChoice(computerChoice));
  19.  
  20.             int result = getResult(userChoice, computerChoice);
  21.             if (result == 0) {
  22.                 System.out.println("It's a tie!");
  23.             } else if (result == 1) {
  24.                 System.out.println("You win!");
  25.             } else {
  26.                 System.out.println("The computer wins!");
  27.             }
  28.  
  29.             System.out.print("Do you want to play again? (y/n): ");
  30.             String playAgainChoice = input.next();
  31.             if (!playAgainChoice.equalsIgnoreCase("y")) {
  32.                 playAgain = false;
  33.             }
  34.         }
  35.     }
  36.  
  37.     public static String getChoice(int choice) {
  38.         switch (choice) {
  39.             case 1:
  40.                 return "rock";
  41.             case 2:
  42.                 return "paper";
  43.             case 3:
  44.                 return "scissors";
  45.             default:
  46.                 return "invalid";
  47.         }
  48.     }
  49.  
  50.     public static int getResult(int userChoice, int computerChoice) {
  51.         if (userChoice == computerChoice) {
  52.             return 0;
  53.         } else if ((userChoice == 1 && computerChoice == 3) || (userChoice == 2 && computerChoice == 1) || (userChoice == 3 && computerChoice == 2)) {
  54.             return 1;
  55.         } else {
  56.             return -1;
  57.         }
  58.     }
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement