Grasshopper Technologies
7228 W. Hood Ave.
Chicago, IL 60631
t: 847 722-4455
info@grasshoppertech.com

Valid XHTML 1.0 Strict

Java Fun! - Chapter 7 - Dice Game

import java.util.Scanner;
import java.util.Random;

public class JavaFun07cDiceGame {
    public static void main(String[] args) {
        Scanner ob=new Scanner(System.in);
        Random rand = new Random(); 
        String play_again = "YES";
        int player_bet = 0;
        int player_total = 0;
        int player_winnings = 0;
        int dice1 = 0;
        int dice2 = 0;
        int diceTotal = 0;
        System.out.println("Ready to play the dice game?");        
        
        while (play_again.equalsIgnoreCase("y") || play_again.equalsIgnoreCase("yes")) {
            System.out.print("\nWhat is your bet? ");
            player_bet=ob.nextInt(); 
            dice1 =  rand.nextInt(6) + 1; 
            dice2 =  rand.nextInt(6) + 1; 
            diceTotal = dice1 + dice2;
            System.out.println("Dice throw is " + diceTotal);
            if (diceTotal == 6 || diceTotal == 12) {
                System.out.println("You tripled your bet!");
                player_winnings = player_bet * 3;
            } else if (diceTotal == 8 || diceTotal == 9) {
                System.out.println("You doubled your bet!");
                player_winnings = player_bet * 2;
            } else if (diceTotal == 7 || diceTotal == 11) {
                System.out.println("You lost!");
                player_winnings = (-1)*player_bet;
            } else {
                System.out.println("No Change");
                player_winnings = 0;                
            }
            player_total = player_total + player_winnings;
            System.out.println("Your total winnings are " + player_total);
            System.out.print("Again (y/n)? ");
            play_again=ob.next();             
        }
    }    
}

run:
Ready to play the dice game?

What is your bet? 10
Dice throw is 9
You doubled your bet!
Your total winnings are 20
Again (y/n)? y

What is your bet? 25
Dice throw is 10
No Change
Your total winnings are 20
Again (y/n)? y

What is your bet? 25
Dice throw is 8
You doubled your bet!
Your total winnings are 70
Again (y/n)? y

What is your bet? 50
Dice throw is 8
You doubled your bet!
Your total winnings are 170
Again (y/n)? y

What is your bet? 10
Dice throw is 12
You tripled your bet!
Your total winnings are 200
Again (y/n)? n
BUILD SUCCESSFUL (total time: 25 seconds)