if else语句中的死分支 [英] Dead branch in if else statement
问题描述
我正在编写这段代码,你给程序命名。
I'm writing this code where you give the the program a name.
Java告诉我语句中的else永远不会被使用如果变量isACoolGuy为false,则使用。
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");
之前有一个switch语句应该将isACoolGuy布尔值更改为false。
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;
推荐答案
你的错误
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");
或更好
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");
在你的情况下最正确的方法是跳过else if并将其替换为其他类似的这个
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");
一些理论
isACoolGuy = true表示为isACoolGuy变量赋值true。
在if中使用它总是返回true
isACoolGuy == true检查变量isACoolGuy是否具有真值。
它的比较
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
在if中你可以跳过比较布尔值,因为if有以下格式
Inside an if you can skip comparing boolean values since if has the following format
if(true)
{
}
所以If(isACoolGuy)类似于if(isACoolGuy == true)
so If(isACoolGuy) is similar to if(isACoolGuy==true)
这篇关于if else语句中的死分支的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!