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;
}
答案 0 :(得分:2)
我不确定在color
内设置if
并在最后设置return
时出了什么问题,但这就是你想要的:
使用以下内容替换if...else
阶梯:
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
这只是使用color
语句切换return
的设置。 (返回内部 if
语句,就像原问题一样。)
这也显示了如何正确使用您在评论中提到的.equals()
方法。
答案 1 :(得分:0)
根据您的要求..这里是代码..
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
}