Write a Java class named Coin. The Coin class should have the following field: •
ID: 3632668 • Letter: W
Question
Write a Java class named Coin. The Coin class should have the following field:• 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-argument constructor that randomly determines the side of the coin that is facing up (“heads” or “tails”) and initializes the sideUp field accordingly.
[note: constructors are described in the early part of Chapter 11 of the Farrell book]
• 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.
Explanation / Answer
public class CoinFlippa { static java.util.Random r = new java.util.Random(); public static void main(String[] args) { new CoinFlippa().run(); } private void run() { Coin coin = new Coin(); for (int i = 0; i < 20; i++) { coin.toss(); System.out.printf("%2d - %s%n", i + 1, coin.getSideUp()); } } // anonymous, inner class // can make a separate file, put both in same folder // cd, to folder then run -- $> java CoinFlippa class Coin { private String sideUp; public Coin() { toss(); } void toss() { sideUp = (r.nextInt(100) % 2 == 0) ? "heads" : "tails"; } public String getSideUp() { return sideUp; } } }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.