private void northroom()
{
    char choice2;
    boolean boolean_1 = false;
    String answer2;
    System.out.println("You press a panel next to the door");
    System.out.println("The panel lights up with a pinging sound");
    System.out.println("The door slowly scrapes open");
    System.out.println("You are now in North Room");
    System.out.println("There is a object in the coner of the room shoraded by darkness");
    do
    {
        System.out.println("Would you like to pick up object Yes(Y) or No(N)");
        while(boolean_1 == false)
        {

            answer2 = keyboard.next();
            choice2 = answer2.charAt(0);
            if(choice2 == 'Y')
            {
                System.out.println("You go pick up the object");
            }
            if(choice2 == 'N')
            {
                    System.out.println("Stare at object because you are useless");
                    System.out.println("Try again");
            }
        }
    }
    while (**choice2** != 'Y' && **choice2** != 'N');


while(choice2!='Y'&& choice2!='N');

在这里,两个choice2都已初始化,我该如何纠正它以便正确循环

最佳答案

编译器的代码路径分析器还不足以识别while(boolean_1 == false)循环将始终至少执行一次。

就编译器而言,可能会跳过循环主体,在这种情况下choice2变量未分配,即未明确分配。

您可以通过将其初始化为虚拟值来解决此问题,例如

char choice2 = ' ';


当然,如果编译器进行了扩展分析,则会发现while(boolean_1 == false)循环永远运行,因为boolean_1从未更新,并且会生成编译错误,指出while (choice2 != 'Y' && choice2 != 'N');无法访问。

关于java - 初始化问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50477578/

10-09 04:57