Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

need a java code for this. The code needs to import random function. The code ca

ID: 3722343 • Letter: N

Question

need a java code for this. The code needs to import random function. The code cannot use non static method or private class. The code is suppose to keep a score

Exercise 3 of 3: Write a program that lets the user play a simple coin flip game against the computer First let the player set the rule for the game (e.g. Heads wins, or Tails wins). Then generate a random outcome of a coin flip for yourself, and one for the computer. Determine the winner. Ask the user if they want to play again, and keep score. Once the user is done playing and decides to quit, present the final score before ending the game.

Explanation / Answer

FlipCoinGame.java

import java.util.Random;

import java.util.Scanner;

public class FlipCoinGame {

public static void main(String[] args) {

Random r = new Random();

Scanner scan = new Scanner(System.in);

System.out

.println("Enter the rule for the game either Heads ot Tails: ");

String rule = scan.next();

int userScore = 0, computerScore = 0, total = 0;

char choice = 'y';

while(choice == 'y' ||choice == 'Y') {

String userChoice = flipCoin(r);

String computerChoice = flipCoin(r);

if(userChoice.equalsIgnoreCase(rule)) {

userScore++;

}

if(computerChoice.equalsIgnoreCase(rule)) {

computerScore++;

}

total++;

System.out.println("Do you want to continue? ");

choice = scan.next().charAt(0);

}

System.out.println("Total Rounds: "+total);

System.out.println("User Score: "+userScore);

System.out.println("Computer Score: "+computerScore);

}

public static String flipCoin(Random r) {

int toss = r.nextInt(2);

if(toss == 1) {

return "Heads";

}

return "Tails";

}

}

Output:

Enter the rule for the game either Heads ot Tails:
Heads
Do you want to continue?
y
Do you want to continue?
y
Do you want to continue?
y
Do you want to continue?
y
Do you want to continue?
y
Do you want to continue?
n
Total Rounds: 6
User Score: 1
Computer Score: 0