2 Replies Latest reply on Jan 6, 2008 8:12 PM by 807601

# [Enums] How to? Method must return a result of type Enum

Hello,
I have a little problem. I write a program as below:
``````
public enum MyColor {
BLACK (0,0,0),
WHITE (255,255,255),
RED (255,0,0),
GREEN (0,255,0),
BLUE (0,0,255),
YELLOW (255,255,0),
CYAN(0,255,255),
MAGENTA (255,0,255);

int r, g, b;

MyColor(int rc, int gc, int bc) {
r=rc; g=gc; b=bc;
}

boolean compare(int rc, int gc, int bc) {
if(this.r==rc && this.g==gc && this.b==bc)
return true;
else return false;
}

public static MyColor giveName(int rc, int gc, int bc) {
for(MyColor tmp: MyColor.values()) {
if(rc==tmp.r && gc==tmp.g && bc==tmp.b) return tmp;
}
}
}``````
and have a question: what is wrong with method giveName(). It must return a color(RED, BLACK, ...) which has the same RGB scheme as integer values of parameters (rc, gc, bc) or return null. How to return this values?
Thanks for all, A.
• ###### 1. Re: [Enums] How to? Method must return a result of type Enum
It's not really an enum problem but more of a method logic problem. Because the return is within an if block, there is a chance that nothing matches the conditions and nothing is returned. For instance what if you have
``MyColor mycolor = MyColor.giveName(5, 5, 5);  ``
You might want to have a default return of null or somesuch:
``````        public static MyColor giveName(int rc, int gc, int bc) {
for(MyColor tmp: MyColor.values()) {
if(rc==tmp.r && gc==tmp.g && bc==tmp.b) return tmp;
}
return null;
}``````
Edited by: Encephalopathic on Jan 6, 2008 12:03 PM
• ###### 2. Re: [Enums] How to? Method must return a result of type Enum
Thanks a lot :) It works.