gpt4 book ai didi

java - 如何在 if 语句中返回字符串?

转载 作者:行者123 更新时间:2023-12-02 04:14:41 24 4
gpt4 key购买 nike

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 中设置 color 并在最后 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

这只是用 return 语句切换 color 的设置。 (返回内部 if 语句,就像最初提出的问题一样。)

这还展示了如何正确使用 .equals() 方法,就像您在评论中询问的那样。

关于java - 如何在 if 语句中返回字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33452555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com