我是学习java的新手,在本例中试图模拟掷骰子游戏。局部变量初始化和开关选择
当我没有初始化变量myPoint
时出现编译器错误,所以我在switch
构造之前将其设置为零。
我想知道为什么我需要声明之后,当它的值设置为开关内sumOfDice
值初始化变量myPoint
,不像gameStatus
变量?
/***** 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
http://stackoverflow.com/questions/1560685/why-must-外可变初始化,例如,分别为
sumOfDice
SEVEN
,因此编译器力local-variables-including-primitives-always-be-initialized-in-java –如果myPoint未初始化,您提供的代码不会失败。您可能会在'default'块之外的某处使用myPoint变量,它可能未初始化。 – pkalinow