首页 > 解决方案 > 如何访问确定 Color 类颜色的三个整数?

问题描述

我需要创建一个不带参数的方法来使颜色变暗,它位于这段代码的底部。它将整数的值调暗 20%。我不知道如何访问在这些 Color 类中创建的整数。我用占位符“a”“b”和“c”代替应该访问确定颜色颜色的三个数字的位置。

public class Color {
final static Color RED = new Color(255, 0 , 0);
final static Color BLACK = new Color(0, 0 , 0);
final static Color GREEN = new Color(0, 255 , 0);
final static Color YELLOW = new Color(255, 255 , 0);
final static Color BLUE = new Color(0, 0 , 255);
final static Color MAGENTA = new Color(202, 31 , 123);
final static Color CYAN = new Color(0, 183 , 235);
final static Color WHITE = new Color(255, 255 , 255);

private int red;
private int green;
private int blue;

public Color(int a, int b, int c) {
    if (a < 0) {
        a = 0;
    }
    if (b < 0) {
        b = 0;
    }
    if (c < 0) {
        c = 0;
    }
    if (a > 255) {
        a = 255;
    }
    if (b > 255) {
        b = 255;
    }
    if (c > 255) {
        c = 255;
    }
    Color custom = new Color(a, b, c);
}


public Color dim() {
    int newA = a * 0.80;
    int newB = b * 0.80;
    int newC = c * 0.80;
    Color newColor = (newA, newB, newC);
    return newColor;
}

它可能必须是 this.Color(0) 或其他东西

另外,我该如何修复这个检查两种颜色是否相同的布尔方法,必须替换“a”。

public boolean equals(Color) {
    if (Color a = Color b){
        return true;
    }
    else {
        return false
    }
}

标签: javacolors

解决方案


您永远不会将参数分配给对象属性,例如...

public Color(int a, int b, int c) {
    red = Math.min(255, Math.max(0, a));
    green = Math.min(255, Math.max(0, b));
    blue = Math.min(255, Math.max(0, c));
}

dim是否需要成为...

public Color dim() {
    int newA = (int)(red * 0.80);
    int newB = (int)(green * 0.80);
    int newC = (int)(blue * 0.80);
    Color newColor = new Color(newA, newB, newC);
    return newColor;
}

因为要修改对象的属性

另外,我该如何修复这个检查两种颜色是否相同的布尔方法,必须替换“a”。

对我来说,这看起来像是一个学习练习,你应该花一些时间来弄清楚,但本质上,你需要确定“其他”类是否是“实例” Color,如果是,属性 ( red, green, blue)相等


推荐阅读