Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 views
in Technique[技术] by (71.8m points)

java - Dead branch in if else statement

I'm writing this code where you give the the program a name.

Java is telling me that the else in the statement is never used when it should be used if the variable "isACoolGuy" is false.

if (isACoolGuy = true){
        System.out.println("Thank you for this name... "+ name);
    }else if(isACoolGuy = false){    
        System.out.println("Okay im changing my name since you are an idiot");
        name = name = "jack";
        System.out.println("My name is "+ name + " now");

There is a switch statement earlier that should change the "isACoolGuy" Boolean to false.

case "name":
            System.out.println("You are an a******");
            isACoolGuy = false;
            break;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

your if is wrong

if (isACoolGuy == true){
        System.out.println("Thank you for this name... "+ name);
    }else if(isACoolGuy == false){
        System.out.println("Okay im changing my name since you are an idiot");
        name = "jack";
        System.out.println("My name is "+ name + " now");

or better

if (isACoolGuy){
        System.out.println("Thank you for this name... "+ name);
    }else if(!isACoolGuy){
        System.out.println("Okay im changing my name since you are an idiot");
        name =  "jack";
        System.out.println("My name is "+ name + " now");

and the most correct way in your case is to skip the else if and replace it with single else like this

if (isACoolGuy){
        System.out.println("Thank you for this name... "+ name);
    }else {
        System.out.println("Okay im changing my name since you are an idiot");
        name =  "jack";
        System.out.println("My name is "+ name + " now");

And some theory

isACoolGuy= true means assign true value to isACoolGuy variable . Using it inside an if always returns true isACoolGuy == true checks if the variable isACoolGuy has true value. It's comparation

Inside an if you can skip comparing boolean values since if has the following format

if(true)
{

}

so If(isACoolGuy) is similar to if(isACoolGuy==true)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...