gpt4 book ai didi

java - 局部变量初始化和开关选择

转载 作者:行者123 更新时间:2023-11-30 08:40:18 26 4
gpt4 key购买 nike

本人初学java,本例尝试模拟掷骰子游戏。

当我没有初始化myPoint 变量时出现编译器错误,所以我在switch 构造之前将它设置为零。

我想明白为什么我需要初始化 myPoint 变量,当它的值设置为 sumOfDice 声明后在 switch 中的值时,不像 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

最佳答案

根据 Java specification

A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16).

rules for switch 语句有效地强制您在 switch 语句的每个可能执行路径中初始化变量。

所以答案是:

  • gameStatus 变量通过 switch 语句在每一个可能的执行路径中被初始化,因此编译器是满意的。
  • myPoint 不会被初始化,例如,如果 sumOfDiceSEVEN,因此编译器会强制您在 switch block 之外初始化变量

关于java - 局部变量初始化和开关选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35747807/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com