1. Member
Join Date
Mar 2008
Posts
16
Rep Power
0

## Color objects

hey all,
am a bit stuck here. basically would like to return the color object so am I right in thinking this is just the rgb values? If not then what would the return type be in the method? i.e. in this case I have put int for the rgb values

Also, what would be the syntax of returning the final three integers, seem to only be able to put one i.e. r in this case and not r,g,b?

Java Code:
```package Chapter4;

import java.awt.*;
import java.util.Random;

public class RandomColor {
public int randomcolor(int r, int g, int b){

return r;

}
public static void main (String []args){
RandomColor pickcolor = new RandomColor();
Random generator = new Random();
int num1 = generator.nextInt(255);
int num2 = generator.nextInt(255);
int num3 = generator.nextInt(255);
int randcolor = pickcolor.randomcolor(num1, num2, num3);
System.out.println(randcolor);
}
}```

2. Below is one solution as far as i understood your problem.

And if you want to return three integers, you can return them as an array in the simplest way (or you can create another object to hold all three integers).

Java Code:
```package Chapter4;

import java.awt.*;
import java.util.Random;

public class RandomColor {

int r, g, b;

private RandomColor(int r, int g, int b) {

this.r = r;
this.g = g;
this.b = b;
}

public static RandomColor createRandomColor(){

Random generator = new Random();
int r = generator.nextInt(255);
int g = generator.nextInt(255);
int b = generator.nextInt(255);

RandomColor c = new RandomColor(r,g,b);
return c;

}

public String toString() {

return "R: "+r+" G: "+g+" B: "+b;

}

public static void main (String []args){

RandomColor pickcolor = RandomColor.createRandomColor();
System.out.println(pickColor);

}
}```

3. Member
Join Date
Mar 2008
Posts
16
Rep Power
0
Thanks for the reply there, but think my level of coding was already at its limit, now am a bit confused ; )

What does the this.r etc do?

4. With 'this' keyword, you are accessing to the class variables. If i do not write 'this' keyword there, i can not change the instance variable of the class. Check parameter names of that method! They are same with class variables' names. In this way, i told compiler which variable to access to eliminate confusion. If you dont want 'this' keyword there just rename method parameters to sth else and remove 'this' keyword.

5. Member
Join Date
Mar 2008
Posts
16
Rep Power
0
ah okay, thanks for the advice : )

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•