简体   繁体   中英

multiple if statements without else

I don't understand why I get a compile error. In my view, this method first evaluates whether n is > 0. When this is the case, then "good" will be assigned to the String object local. However, if this is not the case, then it will not do anything. Next, the method enters another decision construct. This time, it evaluates whether n <= 0. If so, it will assign "bad" to the String object.

In any of both cases, local should be initialized. However, I get a compile error, and the compiler says it may not be initialized. I do not understand where this is coming from.

Note that I know how to correct the second if by replacing it with else and removing the boolean condition. I just don't understand why in a syntax sense this is incorrect.

public class Donkey{
String s1 = "green";

public void generateReport(int n){
    String local;
    if(n > 0)
        local = "good";
    if(n <= 0)
        local = "bad";
    System.out.println(local);
}

The compiler has no way to 'know' that you've handled all the cases with your if statements.

Consider this example (note that the second if is just less than):

String local;
if(n > 0)
    local = "good";
if(n < 0)
    local = "bad";

If n = 0 , then local will not get defined.

The compiler doesn't test your if statements to see if they handle all the cases while compiling.

Changing it to if/else will fix the error as you mentioned. You can also initialize the variable as other users have pointed out.

The problem is that if n is not greater than 0 and is not less or equal than 0 the var local is not initialized. So that is what the compiler is telling you.

You can solve this by initializing the local var with something.

String local = "";

The problem is solved when you use else because for the compiler there can be only 2 possible states, the one if the condition is true and the other if is not, there is no possible third state because the else contemplates all.

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