问题
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;
回答1:
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)
回答2:
Instead of checking if it's true, you are assigning isACoolGuy to true and hence it always evaluates to true.
if (isACoolGuy = true){
Instead use
if (isACoolGuy == true){
Better use:-
if (isACoolGuy)
回答3:
To check the condition should use ==
not =
it's for assignement, like this if(isACoolGuy == true)
.
Try to remove second condition if(isACoolGuy == false)
is not necessasry, it's enough to have key word else
like this:
isACoolGuy = true;
...
if (isACoolGuy){ // the positive control
System.out.println("Thank you for this name... "+ name);
}else{ // otherwise negative
...
}
来源:https://stackoverflow.com/questions/34406303/dead-branch-in-if-else-statement