Question

I'm trying to write a method in Java using basic arithmetic (nothing more advanced than is already in the code) that compares the brightness of (r, g, b) of two pixels, c1 and c2. It needs to pull the (r, g, b) values from c1 and c2, compare and pick the brighter one, and output a third color. Here's what I have:

public static int combineBrighter(Color c1, Color c2) {
        int r = c1.getRed();
        int g = c1.getGreen();
        int b = c1.getBlue();

        int rr = c2.getRed();
        int gg = c2.getGreen();
        int bb = c2.getBlue();

        if(r >= rr){
        int rrr = r;    
        } else if(rr>=r) {
            int rrr = rr;
        }

        if(g >= gg){
            int ggg = g;    
            } else if(gg>=g) {
            int ggg = gg;
            }


        if(b >= bb){
            int bbb = b;    
            } else if(bb>=b) {
                int bbb = bb;
            }
        Color f = new Color(rrr, ggg, bbb);
        return f;

Any ideas why it isn't working? I'm getting an error where rrr, ggg, and bbb can't be inserted to new Color() as ints, but if I switch them to Color or some other type it tells me to switch them back to ints.

Was it helpful?

Solution

It's a scoping problem. Your rrr, ggg, and bbb variables are defined in a scope that's not visible when you use them in the Color constructor.

Declare them earlier in your program.

public static int combineBrighter(Color c1, Color c2) {
    int r = c1.getRed();
    int g = c1.getGreen();
    int b = c1.getBlue();

    int rr = c2.getRed();
    int gg = c2.getGreen();
    int bb = c2.getBlue();

    int rrr;               // declare them in this scope
    int ggg;
    int bbb;

    if(r >= rr){
      rrr = r;             // assign values later
    } else {
       rrr = rr;
    }

    ...

    Color f = new Color(rrr, ggg, bbb);
    return f;

Here's a bit more information about block scope: http://www.cs.umd.edu/~clin/MoreJava/ControlFlow/block.html

However, you could declare and initialise them at the same time by using the ternary ? operator.

int rrr = r >= rr ? r : rr;
int ggg = g >= gg ? r : gg;
int bbb = b >= bb ? r : bb;

But, why re-invent the wheel? This one is much easier to understand:

int maxRed   = Math.max(c1.getRed(),   c2.getRed());
int maxGreen = Math.max(c1.getGreen(), c2.getGreen());
int maxBlue  = Math.max(c1.getBlue(),  c2.getBlue());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top