A String named sideUp. The sideUp field will hold either “heads” or “tails” indi
ID: 3578105 • Letter: A
Question
A String named sideUp. The sideUp field will hold either “heads” or “tails” indicating the side of the coin that is facing up.
The Coin class should have the following methods:
A no-arg constructor that randomly determines the side of the coin that is facing up (“heads” or “tails”) and initializes the sideUp field accordingly.
A void method named toss that simulates the tossing of the coin. When the toss method is called, it randomly determines the side of the coin that is facing up (“heads” or “tails”) and sets the sideUp field accordingly.
A method named getSideUp that returns the value of the sideUp field.
Write a program that demonstrates the Coin class. The program should create an instance of the class and display the side that is initially facing up. Then, use a loop to toss the coin 20 times. Each time the coin it tossed, display the side that is facing up. The program should keep count of the number of times heads is facing up and the number of times tails is facing up, and display those values after the loop finishes.
Java Eclipse
a de up hea da de Up hea tails heads heads Total heads 9, Total tails: 11 array 2) (25 pts) Write a Lottery class that simulates a lottery. The class should have anExplanation / Answer
CoinTest.java
public class CoinTest {
public static void main(String[] args) {
Coin c = new Coin();
int headsCount = 0, tailsCount = 0;
System.out.println("Initial Face in Coin: "+c.getSideUp());
System.out.println("Trial Side Up");
for(int i=1; i<=20; i++){
c.toss();
System.out.println(i+" "+c.getSideUp());
if(c.getSideUp().equalsIgnoreCase("heads")){
headsCount++;
}
else{
tailsCount++;
}
}
System.out.println("Total heads: "+headsCount+", Total tails: "+tailsCount);
}
}
Coin.java
import java.util.Random;
public class Coin {
private String sideUp;
Random r = new Random();
public Coin(){
int randNum = r.nextInt(2);
if(randNum == 1){
sideUp = "heads";
}
else if(randNum == 0){
sideUp = "tails";
}
}
public void toss(){
int randNum = r.nextInt(2);
if(randNum == 1){
sideUp = "heads";
}
else if(randNum == 0){
sideUp = "tails";
}
}
public String getSideUp() {
return sideUp;
}
}
Output:
Initial Face in Coin: tails
Trial Side Up
1 tails
2 heads
3 tails
4 tails
5 tails
6 tails
7 tails
8 tails
9 tails
10 tails
11 heads
12 tails
13 tails
14 heads
15 tails
16 heads
17 heads
18 tails
19 tails
20 heads
Total heads: 6, Total tails: 14
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.