导致java:240的switch语句(可能尚未初始化) [英] Switch statement resulting in java:240 (might not have been initialized)

查看:427
本文介绍了导致java:240的switch语句(可能尚未初始化)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在四处寻找答案,但是没有发现任何真正有助于我的情况的事情:

I have been looking around for an answer for this for a while but haven't found anything that really helps my case so bare with me:

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

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 \n");  
    System.out.print("Do you want Pepperoni? (Y/N): ");
    pepperoni = scan.next().charAt(0);
        break;
    }

我希望变量 topping1 存储值1如果输入为'Y'或'y',如果输入为'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 N n ,你永远不会为<$​​ c $ c> topping1 赋值,因为默认情况从不给它赋值。例如,如果 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 没有给它赋值。 你如何取决于你没有向我们展示的逻辑。您可以为其指定除 0 1 以外的值(您在<$的其他分支中指定的值)例如,c $ c> 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.

这篇关于导致java:240的switch语句(可能尚未初始化)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆