wit4r7
wit4r7

Reputation: 135

How to add values to an object

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.

Upvotes: 1

Views: 1865

Answers (4)

Kevin Anderson
Kevin Anderson

Reputation: 4592

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

Upvotes: 0

Arpit
Arpit

Reputation: 478

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

for example :

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

Upvotes: 0

Mureinik
Mureinik

Reputation: 311798

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

Upvotes: 2

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

Upvotes: 1

Related Questions