Untitled

 avatar
unknown
plain_text
6 months ago
2.3 kB
3
Indexable
import java.util.Random;
import java.util.Scanner;

public class RockPaperScissors {
    
    // Method to generate computer's choice
    public static int computerChoice() {
        Random rand = new Random();
        return rand.nextInt(3); // Returns 0 for Rock, 1 for Paper, 2 for Scissors
    }
    
    // Method to determine the winner of a round
    public static String determineWinner(int userChoice, int compChoice) {
        if (userChoice == compChoice) {
            return "It's a tie!";
        } else if ((userChoice == 0 && compChoice == 2) || 
                   (userChoice == 1 && compChoice == 0) || 
                   (userChoice == 2 && compChoice == 1)) {
            return "You win!";
        } else {
            return "Computer wins!";
        }
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] choices = {"Rock", "Paper", "Scissors"};
        
        int userScore = 0;
        int compScore = 0;
        
        System.out.print("Enter number of rounds: ");
        int rounds = sc.nextInt();
        
        for (int i = 0; i < rounds; i++) {
            System.out.println("\nRound " + (i + 1));
            System.out.println("Choose Rock (0), Paper (1), or Scissors (2): ");
            int userChoice = sc.nextInt();
            
            int compChoice = computerChoice();
            
            System.out.println("You chose: " + choices[userChoice]);
            System.out.println("Computer chose: " + choices[compChoice]);
            
            String result = determineWinner(userChoice, compChoice);
            System.out.println(result);
            
            if (result.equals("You win!")) {
                userScore++;
            } else if (result.equals("Computer wins!")) {
                compScore++;
            }
        }
        
        System.out.println("\nFinal Score: You - " + userScore + ", Computer - " + compScore);
        if (userScore > compScore) {
            System.out.println("You are the overall winner!");
        } else if (userScore < compScore) {
            System.out.println("Computer is the overall winner!");
        } else {
            System.out.println("It's a tie overall!");
        }
        
        sc.close();
    }
}
Editor is loading...
Leave a Comment