Beep Boop
Beep Boop

Reputation: 1

Initialising Issue

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');

Here both the choice2 are initialised how do I correct this so that it loops properly

Upvotes: 0

Views: 25

Answers (2)

Andreas
Andreas

Reputation: 159086

The compilers code-path analyzer doesn't go far enough to recognize that the while(boolean_1 == false) loop will always execute at least once.

As far as the compiler is concerned, the loop body might be skipped, in which case the choice2 variable is unassigned, i.e. not definitely assigned.

You can fix that by initializing it to a dummy value, e.g.

char choice2 = ' ';

Of course, if the compiler did extended analysis, it would have found that the while(boolean_1 == false) loop runs forever, since boolean_1 is never updated, and would have generated compile error saying that while (choice2 != 'Y' && choice2 != 'N'); is unreachable.

Upvotes: 1

SwordW
SwordW

Reputation: 610

I'm not sure what is the designed behavior for your nested loops. However, ur inner loop is a infinite loop. It can never end so outer loop can never check condition showed in last line of code

Upvotes: 0

Related Questions