1
votes

I try to learn Java and have a question. I created a class Color. This class contains an constructor for "color" with 3 int values (red, green, blue). Then I have an array with a lot of color elements.

Now I want to add 4 of this elements to one and divide it, so I get the average of each int value.

But eclipse says, that the operator + is undefined.

Color sum = new Color(red, green, blue)
for (int i = 0; i < length; i ++) {
     sum = sum + array[i];
}

public Color(int r, int g, int b){
    this.red=r;
    this.green=g;
    this.blue=b;
}

How can I add the values of each array element to a sum? The elements in the array are from the type color.

4
the sum is not defined for your object, if it contained a string what should java do ? You have to sum the red,green,blue values manuallyOmar Aflak
When you say "an array of color elements", did you mean Color, i.e., your class Color?Kevin Anderson

4 Answers

2
votes

There is no operator overloading in Java. You'd have to handle each value separately:

int avgRed = 0;
int avgGreen = 0;
int avgBlue = 0;
for (int i = 0; i < length; i ++) {
    avgRed += array[i].getRed();
    avgBlue += array[i].getBlue();
    avgGreen += array[i].getGreen();
}
Color avgColor = new Color(avgRed / length, avgBlue / length, avgGreen / length);
1
votes

sum variable is a Color and the concatenation in the form

sum = sum + array[i];

is not defined, so the compiler can not understand how to resolve such operation

you could maybe consider something like

sum.red +=  array[i];

is array[i] is holding an integer or:

sum.red +=  array[i].red;

if the array is an array of colors

0
votes

Sum is an object not variable.You can add value to its associated parameter.

for example :

sum.red = sum.red+array[i].red
0
votes

You can't use the + operator to do what you have in mind, but you could add an add method to your Color class so that you could then write:

Color sum = new Color(red, green, blue)
 for (int i = 0; i < length; i ++) {
    sum = sum.add(array[i]);

Let's assume for this discussion that adding Colors means we add the red part of the one to the red part of the other, green to green, blue to blue. Your add method would look like this:

    public Color add(Color other) {
        return new Color(this.red + other.red, 
                         this.green + other.green,
                         this.blue + this.blue);
    }