简体   繁体   中英

Why is an Unreachable code error in this sequence of code and not the latter?

public String motorNoise() {
    String[] ignition={"vroom","pop","bang"};
    engineNoise=(int)(Math.random()*3);
    startEngine=ignition[engineNoise];
    if (engineNoise==2)
        System.out.println("This car needs a service");
    return startEngine;
    
        
    }

But this sequence causes an Unreachable code error. Why is the location of the If statement causing the method to fail?

public String motorNoise() {
    String[] ignition={"vroom","pop","bang"};
    engineNoise=(int)(Math.random()*3);
    startEngine=ignition[engineNoise];
    
    return startEngine;
    
    if (engineNoise==2)
        System.out.println("This car needs a service");
        
    }
    
        

Because in the first example, if you take all possible paths through the method, all statements will be executed.

However, in your second example, the if statement can never be executed:

public String motorNoise() {
    String[] ignition={"vroom","pop","bang"};
    engineNoise=(int)(Math.random()*3);
    startEngine=ignition[engineNoise];
    
    return startEngine; // <-- EXECUTED UNCONDITIONALLY, FUNCTION TERMINATES
    
    if (engineNoise==2)
        System.out.println("This car needs a service");        
}

return startEngine is always executed unconditionally and immediately terminates execution of the function. There's no way for if (engineNoise == 2) to be executed.

NB. It always pays off to properly format and indent your code and to use braces. Your first example

public String motorNoise() {
    String[] ignition={"vroom","pop","bang"};
    engineNoise=(int)(Math.random()*3);
    startEngine=ignition[engineNoise];
    if (engineNoise==2)
        System.out.println("This car needs a service");
    return startEngine;
}

Is actually:

public String motorNoise() {
    String[] ignition={"vroom","pop","bang"};
    engineNoise=(int)(Math.random()*3);
    startEngine=ignition[engineNoise];
    if (engineNoise==2) {
        System.out.println("This car needs a service");
    }
    return startEngine;
}

so it is not only the order of lines, but the nesting of your code blocks that affects execution. Anything inside the body of an if-statement is only executed conditionally.

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