为什么会说' decimalNum'可能尚未初始化,虽然它已在switch语句中的一个案例中初始化了?
Scanner s = new Scanner(System.in);
char romeDigit;
int decimalNum;
boolean inputValid = true;
System.out.println("Please enter a rome digit: ");
romeDigit = s.next().charAt(0);
switch (romeDigit) {
case 'i':
case 'I':
decimalNum = 1;
break;
case 'v':
case 'V':
decimalNum = 5;
break;
case 'x':
case 'X':
decimalNum = 10;
break;
default:
inputValid = false;
break;
}
if (inputValid)
System.out.println**("Num is" + decimalNum);**
else
System.out.println("Invalid input!");
答案 0 :(得分:1)
在某些情况下初始化decimalNum
还不够。必须在所有情况下对其进行初始化,包括默认情况。
default:
inputValid = false;
decimalNum = -1; // it doesn't really matter what you put here, since
// you are using a flag to determine if the value is valid
break;
答案 1 :(得分:-1)
或者只是添加int decimalNum = 0;在哪里声明变量以避免错误