java - 运行来自多个 If Else 语句时的多个结果
问题描述
当用户输入两种原色时,我试图让它混合颜色。我遇到的问题是结果返回多个结果,其中一些结果不正确。如果用户输入红色和黄色这两种颜色,它将打印甚至只有其中一种颜色的结果。
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
System.out.println("Please pick a primary color:");
Scanner color = new Scanner(System.in);
String input = color.next();
System.out.println("Please pick another primary color:");
String input2 = color.next();
{
if(input.equals("Red")||input.equals("red")&&input2.equals("Blue")||
input2.equals("blue"))
{
System.out.println("Red and Blue make Purple.");
}
else if(input.equals("Blue")||input.equals("blue")&&input2.equals("Red")||
input2.equals("red"))
{
System.out.println("Blue and Red make Purple.");
}
else if(input.equals("Blue")||input.equals("blue")&&input2.equals("Yellow")||
input2.equals("yellow"))
{
System.out.println("Blue and Yellow make Green.");
}
else if(input.equals("Yellow")||input.equals("yellow")&&input2.equals
("Blue")||input2.equals("blue"))
{
System.out.println("Yellow and Blue make Green.");
}
else if(input.equals("Yellow")||input.equals("yellow")&&input2.equals
("Red")||input2.equals("red"))
{
System.out.println("Yellow and Red make Orange.");
}
else if(input.equals("Red")||input.equals("red")&&input2.equals
("Yellow")||input2.equals("yellow"))
{
System.out.println("Red and Yellow make Orange.");
}
else
{
System.out.println("Enter a Valid Primary colors.");
}
}
}
}
解决方案
你给定的条件是错误的。它应该是:
if(input.equalsIgnoreCase("red") && input2.equalsIgnoreCase("Blue"))
{
System.out.println("Red and Blue make Purple.");
}
else if(input.equalsIgnoreCase("blue") && input2.equalsIgnoreCase("Red")
{
System.out.println("Blue and Red make Purple.");
}
else if(input.equalsIgnoreCase("blue") && input2.equalsIgnoreCase("Yellow"))
{
System.out.println("Blue and Yellow make Green.");
}
else if(input.equalsIgnoreCase("yellow") && input2.equalsIgnoreCase("blue"))
{
System.out.println("Yellow and Blue make Green.");
}
else if(input.equalsIgnoreCase("yellow") && input2.equalsIgnoreCase("Red"))
{
System.out.println("Yellow and Red make Orange.");
}
else if(input.equalsIgnoreCase("red") && input2.equalsIgnoreCase("Yellow"))
{
System.out.println("Red and Yellow make Orange.");
}
else
{
System.out.println("Enter a Valid Primary colors.");
}
那为什么你的条件不对呢?
好吧,您正在检查是否statement1 is true OR (statement1 & 2 is true) OR statement2 is true
. 结果,如果这三个由 OR 连接的段中的任何一个为真,则整个条件为真。
例如,在您的第一个条件中,您给出了:
if(input.equals("Red") || input.equals("red") && input2.equals("Blue") || input2.equals("blue"))
因此,如果用户输入红色和黑色,则整个条件都将满足,因为第一部分input.equals("Red")
为真。这就是为什么你会得到"Red and Blue make Purple."
希望你明白这里发生了什么。
推荐阅读
- r - 在R中逐页将多个excel文件附加到一个excel文件中
- python - BeautifulSoup 如何从公众号获取所有推文?
- google-app-maker - 是否可以设置需要的下拉小部件?
- javascript - 进行动态点击
- c# - 如何将参数传递给 Azure 函数
- angular - Typescript 2.7.2:阅读此错误消息时遇到问题
- sql - 将 2K18 年转换为 2018 年
- javascript - 反应中的星级评分组件
- scala - 将 jar 添加到 spark-submit 以在 Hive 中使用它
- oracle - 无法将修改保存到服务器。返回错误:'未注册提供程序'OraOLEDB.Oracle'