Search code examples
javaif-statementmethodsreturn

How do I return my string inside an if statement?


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;
}

Solution

  • I'm not sure what's wrong with setting the color inside the ifs and returning it at the end, but here is what you wanted:

    Replace your if...else ladder with the following:

    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
    

    This simply switches out the setting of color with a return statement. (Returning inside the if statements like the original question asked.)

    This also shows how to properly use the .equals() method like you asked in the comment.