简体   繁体   中英

Local string variable not initializing error

Why are the variable q2,q3 not being initialized, yet q1 is?

This is how the outcome should be similar to:

WELCOME TO MITCHELL'S TINY ADVENTURE!

You are in a creepy house! Would you like to go "upstairs" or into the "kitchen"?

kitchen

There is a long countertop with dirty dishes everywhere. Off to one side there is, as you'd expect, a refrigerator. You may open the "refrigerator" or look in a "cabinet".

refrigerator

Inside the refrigerator you see food and stuff. It looks pretty nasty. Would you like to eat some of the food? ("yes" or "no")

no

import java.util.Scanner;

public class App1 {

    public static void main(String[] Args) {

        Scanner keyboard = new Scanner(System.in);

        String q1;
        String q2;
        String q3;

        String a = "upstairs";
        String b = "kitchen";
        String c = "refrigerator";
        String d = "cabinet";
        String e = "yes";
        String f = "no";
        String g = "hallway";
        String h = "bedroom";
        String i = "bathroom";

        System.out.println("Welcome To Mitchell's Tiny Adventure!");
        System.out.println();
        System.out.println("You are in a creepy house, would you like to go upstairs or into the kitchen?");
        System.out.print(">");
        q1 = keyboard.nextLine();
        System.out.println();
        if (q1.equals(a)) {
            System.out.println("Upstairs you see a hallway.  At the end of the hallway is the master");
            System.out.println("\"bedroom\".  There is also a \"bathroom\" off the hallway.  Where would you like");
            System.out.println("to go?");
            System.out.print(">");
            q2 = keyboard.nextLine();
            System.out.println();

        } else if (q1.equals(b)) {
            System.out.println("There is a long countertop with dirty dishes everywhere. Off to one");
            System.out.println("side there is, as you'd expect, a refrigerator. You may open the \"refrigerator\"");
            System.out.println("or look in a \"cabinet\".");
            System.out.print(">");
            q2 = keyboard.nextLine();
            System.out.println();

        }
        if (q2.equals(c)) {
            System.out.println("Inside the refrigerator you see food and stuff.  It looks pretty nasty.");
            System.out.println("Would you like to eat some of the food? (\"yes\" or \"no\")");
            System.out.print(">");
            q3 = keyboard.nextLine();
            System.out.println();
        } else if (q2.equals(d)) {
            System.out.println("Inside the cabinet is the boogie man, Are you scare? \"yes or no\"");
            q3 = keyboard.nextLine();
            System.out.println();

        }if (q2.equals(g)){
            System.out.println("You fall in the hallway can you make it? \"yes or no\"");
            q3 = keyboard.nextLine();
            System.out.println();
        }else if (q2.equals(h)){
            System.out.println("You run into the bedroom were there are monsters live are you afraid \"yes or no\"");
            q3 = keyboard.nextLine();
            System.out.println();
        }else if(q2.equals(i)){
            System.out.println("You run into the bathroom do you have to use it \"yes or no\"");
            q3 = keyboard.nextLine();
            System.out.println();
        }

    }       
}

Every variable needs to be initialized, before it is accessed the very first time. This can happen automatically for constants and fields, but it needs to be done manually for local variables. So the developers has to decide which value should be the first value for a variable. Mostly it is either null (for object types) or 0 / false (for primitive types).

So, now about your question:

Why are the variable q2,q3 not being initialized, yet q1 is?

About q1 : the first time you try to read the reference "in" that variable is here:

if (q1.equals(a)) {

but before that, you're having this assignment:

q1 = keyboard.nextLine();

Here you initialize the variable q1 with the returned reference of the keyboard.nextLine() method call.

Now about q2 :
(The problem with q2 and q3 are the same, so I just focus on q2 ).

You have this assignment in both the if and the else if block:

q2 = keyboard.nextLine();

So you try to assign it to another user input if q1 equals "upstairs" or "kitchen" . But what will q2 be, if q1 is neither of them? Maybe it is "garden" or "downstairs" , then q2 will remain uninitialized and the compiler can detect that, hence the error.

You must think about what to do if q1 is neither of them. You could ask the user again, until you get a valid answer. Or you can exit the program, if such situation is not allowed. It is up to you.

You could also initialize q2 and q3 with a certain default value to avoid that error and to avoid unexpected exceptions like a NullPointerException . It can be done like this:

String q2 = "";
String q3 = "";

In the first section, if all your tests for q1 were false, q2 would remain uninitialized, but you reference q2 in the 2nd section; similarly for q3 .

If a code path exists that allows a local variable to be referenced without first being initialized, this compile error will occur.

Note that the compiler does not examine the logic aspects of the code, so for example this will fail to compile:

String a = "foo";
String s;
if (a.equals("foo")) {
    s = "bar";
} else if (!a.equals("foo")) {
    s = "baz";
}
System.out.println(s); // error

Even though we can see that logically s must be initialized, the compiler sees only boolean methods, which may result in s not being assigned.

You must initialize local variables before you use them. Try

String q1 = "";
String q2 = "";
String q3 = "";

well in line 42 : if (q2.equals(c)) {
and in line 53 : } else if (q2.equals(d)) { you attempt to call the equals() method in an uninitialized variable ( String q2 ) , try to initialize them first or check them for null values , it depends on how you want to handle each case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM