switch 语句后的初始化

initialization after switch-statement

为什么说'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!");

在某些情况下,初始化 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;

或者只添加 int decimalNum=0;在哪里声明变量以避免错误