// A game of (European) roulette. // // Notice the usage of the && and || operators, the tracking of the maximum bank, // the mixed String/numerical input, and the usage of random numbers. // In particular, notice that only one Random object is created, and it is passed // as a parameter. import java.util.*; public class Roulette { public static void main(String[] args) { Scanner console = new Scanner(System.in); Random rand = new Random(); int bank = 100; int max = bank; int spins = 0; System.out.println("Let's play roulette!"); while (bank > 0) { int bet = getBet(console, bank); String choice = getChoice(console); boolean result = spinWheel(rand, choice); if (result) { bank += bet; } else { bank -= bet; } spins++; max = Math.max(max, bank); } System.out.println("You played " + spins + " times and could have had $" + max); } // Ask for and return the user's bet, limiting the bet at the user's current bankroll. // // Scanner console - the Scanner to use for input // int bank - the amount of money the user currently has public static int getBet(Scanner console, int bank) { System.out.print("You currently have $" + bank + ". Your bet? $"); int bet = console.nextInt(); if (bet > bank) { System.out.println("You don't have that much. Betting $" + bank + " instead."); bet = bank; } return bet; } // Ask whether the user will bet on high or low and return the answer, // rejecting all other responses. // // Scanner console - the Scanner to use for input public static String getChoice(Scanner console) { System.out.print("Bet on high or low? "); String choice = console.next(); while (!choice.equalsIgnoreCase("high") && !choice.equalsIgnoreCase("low")) { System.out.print("Invalid bet. High or low?"); choice = console.next(); } return choice; } // Simulate a single spin of the roulette wheel and return whether or not // the player won their bet. // // Random r - the Random object to use // String bet - whether the player bet on high or low public static boolean spinWheel(Random r, String bet) { int spin = r.nextInt(37); System.out.print("Spin was: " + spin + ". "); if ((bet.equals("high")&& spin > 18) || (bet.equals("low") && spin <= 18 && spin != 0)) { System.out.println("You won!!!!"); return true; } else { System.out.println("You lost."); return false; } } }