import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; /* Java application that "exercises" the classes in the "Coin class hierarchy". ** ** Author: R. McCloskey ** Date: January 2024 */ public class CoinTester { private static Scanner input; private static boolean echo; public static void main(String[] args) { establishInput(args.length == 0 ? null : args[0]); System.out.println("Welcome to the CoinTester program.\n"); int seed = getInt("Enter seed: "); int numTosses = getInt("Enter # times to toss coins: "); int headPercent = getInt("Enter HEADS probability as an int percent: "); double headProb = headPercent / 100.0; // Create an array of three coin objects, one from each of the three // classes in the "Coin hierarchy". Coin[] coins = new Coin[] { new Coin(seed), new BiasedCoin(seed, headProb), new BiasedCoinWithCounts(seed, headProb) }; // Toss each coin the specified # of times; after each toss, report its // current state (using the String returned by its toString() method). for (int i=1; i <= numTosses; i++) { for (int j = 0; j != coins.length; j++) { coins[j].toss(); System.out.printf("\nAfter %d tosses, coin[%d]:\n%s\n", i, j, coins[j]); } } System.out.println("\nGoodbye from the CoinTester program."); } /* Assigns to the 'input' Scanner object the intended source of ** input data. If the given string provides the name of a file, ** that file will be the input source. Otherwise the input source ** will be the keyboard. */ private static void establishInput(String fileName) { if (fileName == null) { input = new Scanner(System.in); echo = false; } else { try { input = new Scanner(new File(fileName)); } catch (FileNotFoundException e) { e.printStackTrace(System.out); System.out.println("Program aborting"); System.exit(0); } echo = true; } } /* Displays the given prompt and returns the integer response, as ** read by the 'input' Scanner. */ private static int getInt(String prompt) { int result; System.out.print(prompt); result = input.nextInt(); if (echo) { System.out.println(result); } return result; } }