I'm novice in learning java, in this example that try to simulate roll dice game.
Compiler error appears when I do not initialize myPoint
variable, so I set it to zero before switch
construct.
I want to understand why do I need to initialize myPoint
variable when it's value is set to value of sumOfDice
within switch after it is declared, Unlike gameStatus
variable?
/***** roll dice game ****/
//some code here..
private enum Status { CONTINUE, WON, LOST };
// plays one game of craps
public static void main( String[] args )
{
// point if no win or loss on first roll
int myPoint = 0;
Status gameStatus; // can contain CONTINUE, WON or LOST
int sumOfDice = rollDice(); // first roll of the dice
// determine game status and point based on first roll
switch ( sumOfDice )
{
case SEVEN: // win with 7 on first roll
case YO_LEVEN: // win with 11 on first roll
gameStatus = Status.WON;
break;
case SNAKE_EYES: // lose with 2 on first roll
case TREY: // lose with 3 on first roll
case BOX_CARS: // lose with 12 on first roll
gameStatus = Status.LOST;
break;
default: // did not win or lose, so remember point
gameStatus = Status.CONTINUE; // game is not over
myPoint = sumOfDice; // remember the point
System.out.printf( "Point is %d\n", myPoint );
break; // optional at end of switch
} // end switch
// rest of the code here ..
// display won or lost message
// roll dice, calculate sum and display results
public static int rollDice()
{
// return sum of dice
}
} // end class Craps