Over-complication? Yes, you really :-)
I would just use a lot easier:
public String seeColor (String color) { if (color.startsWith("red")) return "red"; if (color.startsWith("blue")) return "blue"; return ""; }
The following complete program shows this in action:
public class Test { public static String seeColor (String color) { if (color.startsWith("red")) return "red"; if (color.startsWith("blue")) return "blue"; return ""; } public static void main(String[] args) { String[] testData = { "redxx", "xxred", "blueTimes", "NoColor", "red", "re", "blu", "blue", "a", "", "xyzred" }; for (String s: testData) System.out.println("[" + s + "] -> [" + seeColor(s) + "]"); } }
The output of this program, as expected:
[redxx] -> [red] [xxred] -> [] [blueTimes] -> [blue] [NoColor] -> [] [red] -> [red] [re] -> [] [blu] -> [] [blue] -> [blue] [a] -> [] [] -> [] [xyzred] -> []
If you want it to be easily extensible in the future, you could choose something like:
public static String seeColor (String color) { String[] allow = {"red", "blue"}; for (String s: allow) if (color.startsWith(s)) return s; return ""; }
Then adding color to the allow array is the only step you need to take to recognize it.
source share