导致 java:240 的 switch 语句(可能尚未初始化)

2022-01-19 00:00:00 default switch-statement java

我正在尝试根据输入将值存储在变量中:

I am trying to store a value inside a variable depending on the input:

switch(pepperoni) {

    case 'Y':
    case 'y':
        topping1 = 1;
        break;

    case 'N':
    case 'n':   
        topping1 = 0;
        break;

    default: 

        {
    System.out.print("This is not a valid response, please try again 
");  
    System.out.print("Do you want Pepperoni? (Y/N): ");
    pepperoni = scan.next().charAt(0);
        break;
    }

我希望变量 topping1 如果输入为Y"或y"则存储值 1,如果输入为N"或n"则存储值 0

I want the variable topping1 to store the value 1 if the input is 'Y' or 'y' and to store the value 0 if the input is 'N' or 'n'

如果输入既不是Y"、y"、N"也不是n",那么我希望它重复问题,直到输入有效的输入.

If the input is neither 'Y', 'y', 'N' nor 'n' then I want it to repeat the question until a valid input is typed in.

当我稍后在程序中尝试打印值因为它可能尚未初始化"时,问题就出现了,这在某种程度上是有道理的.(下例)

The problem arises when I later in the program try to print the value 'because it might have not been initialized', which somewhat makes sense. (example below)

if(topping1 > 0)
    System.out.println("Pepperoni"); 

// 243: error: variable topping1 might not have been initialized

我确实意识到还有其他方法可以做到这一点,但由于我真的很想学习 Java,所以我尝试尽可能多地了解基础知识.因此,如果有人能告诉我为什么这不起作用以及是否有办法通过 switch 语句或快速修复来做到这一点,我会非常高兴.

I do realize there are other ways to do this, but as I am really wanting to learn Java I try to understand as much of the fundamentals as possible. Therefore would I be really happy if someone could tell me why this not work and if there is a way to do this with a switch statement or quick fixes.

推荐答案

如果 pepperoni 不是 Y, y, Nn,你永远不会给 topping1 赋值,因为 default 的情况永远不会给它赋值.例如,如果 pepperoni 不是这四个值之一,则控制流会跳过其他两种情况并转到 default,它永远不会给出 topping1 一个值,所以稍后当你尝试使用它时,可能 topping1 根本就没有收到过一个值.

If pepperoni is not Y, y, N, or n, you never assign a value to topping1, because the default case never assigns it a value. E.g., if pepperoni is not one of those four values, then the flow of control skips the other two cases and goes to default, which never gives topping1 a value, so later when you try to use it, it's possible topping1 has never received a value at all.

解决方法"是更正逻辑,这样您就永远不会在未为其分配值的情况下尝试使用 topping1.如何你这样做取决于你没有向我们展示的逻辑.例如,您可以为其分配一个不同于 01 的值(您在 switch 的其他分支中分配的值).

The "workaround" is to correct the logic so that you never try to use topping1 without having assigned it a value. How you do that depends on logic you haven't shown us. You might assign it a value other than 0 or 1 (the values you assign in the other branches of the switch), for instance.

相关文章