Java 如何在if语句中返回字符串?
按照你的要求。。这是密码Java 如何在if语句中返回字符串?,java,if-statement,methods,return,Java,If Statement,Methods,Return,按照你的要求。。这是密码 public static String mixColors1(String x, String y) { String red="red"; String yellow="yellow"; String blue="blue"; String color = null;//this line... is an issue if(red == x && yellow == y || red == y &&
public static String mixColors1(String x, String y)
{
String red="red";
String yellow="yellow";
String blue="blue";
String color = null;//this line... is an issue
if(red == x && yellow == y || red == y && yellow == x)//if red&yellow selected
color = "orange";//return orange
else if(red == x && blue == y || red == y && blue == x)//if red&blue selected
color = "purple";//return purple
else if(yellow == x && blue == y || yellow == y && blue == x)//if blue&yellow selected
color = "green";//return green
return color;
}
我不确定在
if
s中设置颜色
并在结尾处返回会有什么问题,但下面是您想要的:
将您的if…else
梯形图替换为以下内容:
public static String mixColors1(String x, String y)
{
String red="red";
String yellow="yellow";
String blue="blue";
if(red.equals(x) && yellow.equals(y) || red.equals(y) && yellow.equals(x))//if red&yellow selected
return "orange";//return orange
else if(red.equals(x) && blue.equals(y) || red.equals(y) && blue.equals(x))//if red&blue selected
return "purple";//return purple
else if(yellow.equals(x) && blue.equals(y) || yellow.equals(y) && blue.equals(x))//if blue&yellow selected
return "green";//return green
else
return null; //if color won't match it will return null
}
这只需使用return
语句切换color
的设置。(返回if
语句内部,如原始问题。)
这还显示了如何正确使用注释中所要求的.equals()
方法。首先,不要将字符串与=
进行比较。使用equals(…)
方法。此代码有什么问题?为什么要将返回值放在if语句中?请给我一个等式(..)的例子好吗?@Weiner我在下面给出了示例代码。如果其中一种颜色既不是红色、蓝色也不是黄色,则将为空。这并不能回答最初的问题。您是对的。我给他解释了他的逻辑哪里是错的,假设哪里是错的。这样他就可以从错误中学习。但是你仍然没有让它从ifs中返回。我们只返回一条基于if else条件的语句。请查看java文档以了解更多详细信息。@RamPrakash如果这些现在是我答案的精确副本:(@I.C.Weiner您可以有多个返回
s!但是,方法遇到的第一个将是将其从方法中分离出来的一个。因此您可以有多个返回
s,但只会执行一个。@I.C.Weiner没问题!我很高兴我提供了帮助(如果我提供了,请务必接受)!
if(red.equals(x) && yellow.equals(y) || red.equals(y) && yellow.equals(x))//if red&yellow selected
return "orange";
else if(red.equals(x) && blue.equals(y) || red.equals(y) && blue.equals(x))//if red&blue selected
return "purple";
else if(yellow.equals(x) && blue.equals(y) || yellow.equals(y) && blue.equals(x))//if blue&yellow selected
return "green";
else
return null; // default value, if neither orange nor purple nor green