Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 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 Answer

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...