Site icon

Create Rock Paper Scissor Game in Java

History of Rock Paper Scissor game

The origins of Rock-Paper-Scissors can be traced back to ancient hand games found in various cultures throughout history. Its exact origins are unclear, but similar hand games were played in China, Japan, and other regions for centuries. The game gained popularity in Japan, where it was known as “Janken.”

In the West, its earliest known mention dates back to the 17th century in Italy. Variants of the game were also documented in historical texts in England and France. The game’s simplicity and ease of play contributed to its widespread adoption and enduring popularity.

What are rules of rock paper scissor game?

Rock Paper Scissor

How to create Rock Paper Scissor Game in Java?

Play Rock Paper Scissor Game in Java

import java.util.Random;
import java.util.Scanner;

enum Choice {
    ROCK, PAPER, SCISSORS;

    public static Choice getRandom() {
        return values()[new Random().nextInt(values().length)];
    }
}

public class RockPaperScissors {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Choice[] choices = Choice.values();

        while (true) {
            System.out.println("Enter your choice (ROCK, PAPER, or SCISSORS): ");
            String userInput = scanner.nextLine().toUpperCase();

            Choice playerChoice;
            try {
                playerChoice = Choice.valueOf(userInput);
            } catch (IllegalArgumentException e) {
                System.out.println("Invalid input. Please enter ROCK, PAPER, or SCISSORS.");
                continue;
            }

            Choice computerChoice = Choice.getRandom();

            System.out.println("Your choice: " + playerChoice);
            System.out.println("Computer's choice: " + computerChoice);

            if (playerChoice == computerChoice) {
                System.out.println("It's a tie!");
            } else if ((playerChoice == Choice.ROCK && computerChoice == Choice.SCISSORS) ||
                    (playerChoice == Choice.PAPER && computerChoice == Choice.ROCK) ||
                    (playerChoice == Choice.SCISSORS && computerChoice == Choice.PAPER)) {
                System.out.println("You win!");
            } else {
                System.out.println("Computer wins!");
            }

            System.out.println("Do you want to play again? (yes/no)");
            String playAgain = scanner.nextLine().toLowerCase();
            if (!playAgain.equals("yes")) {
                break;
            }
        }

        scanner.close();
    }
}

Output: Created Rock Paper Scissor Game in Java

Enter your choice (ROCK, PAPER, or SCISSORS):
rock
Your choice: ROCK
Computer's choice: SCISSORS
You win!
Do you want to play again? (yes/no)
yes
Enter your choice (ROCK, PAPER, or SCISSORS):
paper
Your choice: PAPER
Computer's choice: PAPER
It's a tie!
Do you want to play again? (yes/no)
no
Exit mobile version