Rock-Paper-Scissors Java Game

Rock-Paper-Scissors Java Game

Write a Java program that simulates a Rock-Paper-Scissors game. The program should allow the user to play 5 rounds against the computer. At the end of the 5 rounds, it should display the final scores and declare the winner.

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

import static java.lang.System.in;

public class demo {
    public static void main(String[] args) {

        int userScore = 0;
        int compScore = 0;
        int tie = 0;

        for(int i = 0; i<5; i++){
            Random randomNum = new Random();
            int rand_int = randomNum.nextInt(90);
            Scanner input = new Scanner(in);

            System.out.println("Round: "+ (i+1)+"\nType \"R\" for Rock, \"P\" for Paper & \"S\" Scissor");
            char userInput = input.next().charAt(0);

            char comp_input;

            // computer response logic
            if(rand_int > 0 && rand_int <= 30){
                comp_input = 'R';
            } else if (rand_int > 30 && rand_int <= 60) {
                comp_input = 'P';
            }
            else {
                comp_input = 'S';
            }

            // game rule logic
            if(comp_input == 'S' &&  userInput == 'P'){
                System.out.println("*****Computer Won*****");
                compScore++;
            } else if (comp_input == 'P' &&  userInput == 'R') {
                System.out.println("*****Computer Won*****");
                compScore++;
            } else if (comp_input == 'R' &&  userInput == 'S') {
                System.out.println("*****Computer Won*****");
                compScore++;
            } else if (userInput == 'S' && comp_input =='P') {
                System.out.println("*****You won*****");
                userScore++;
            } else if (userInput == 'P' && comp_input =='R') {
                System.out.println("*****You won*****");
                userScore++;
            } else if (userInput == 'R' && comp_input =='S') {
                System.out.println("*****You won*****");
                userScore++;
            }
            else {
                System.out.println("Both User and Computer choose same thing, its a tie");
                tie++;
            }


            System.out.println("---------------------------------------------------------");
        }// for loop block


        if (userScore==compScore){
            System.out.println("This Series is tied with: "+userScore +"-"+ compScore);
        } else if (userScore>compScore) {
            System.out.println("You won with: "+userScore +"-"+ compScore+ ", Tie: "+tie);
        }else {
            System.out.println("Computer Won with: "+compScore +"-"+ userScore+ ", Tie: "+tie);
        }


    }// write all the code above this line
}

Did you find this article valuable?

Support Gulshan Kumar by becoming a sponsor. Any amount is appreciated!