【问题标题】:How do I access the three ints that determine the Color class' color?如何访问确定 Color 类颜色的三个整数?
【发布时间】:2020-01-31 04:24:49
【问题描述】:

我需要创建一个不带参数的方法来使颜色变暗,它位于这段代码的底部。它将整数的值调暗 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
    }
}

【问题讨论】:

  • 你不认为这将是递归的Color custom = new Color(a, b, c);
  • 你能更好地解释你的问题吗? IE。您在哪条线路上遇到问题?
  • 您永远不会将红色、绿色、蓝色值分配给它们的属性(即this.red = a
  • 我知道为什么那会是递归的
  • @SkiMaskTheSlumpGod Color 调用Color,后者调用Color ...好吧,你明白了

标签: java colors


【解决方案1】:

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

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 的“实例”,如果是,如果属性(redgreenblue)相等

【讨论】:

  • 令人惊奇的是我写了一个看起来几乎完全一样的答案(包括Math.minMath.max 链,没有看到你的答案)。您在Color newColor = new Color(newA, newB, newC); 错过了new Color,并且忘记分配给newA-newC
  • @ElliottFrisch 是的,我使用 min(max) 来限制范围的次数真是令人惊讶 ? - 认为注意到我错过的东西
  • @ElliottFrisch ? 斯威夫特太多了?
  • if (this.red == Color.red && this.green == Color.green && this.blue == Color.blue) { ?
  • @SkiMaskTheSlumpGod 不,不是真的。好的,Objectequals 定义为public void equals(Object other),因此,假设您要覆盖此方法,您需要测试您传递给equals 的对象实例是否实际上是Color目的。但是,如果您只是在创建一个新方法public void equals(Color color),那么您就在正确的轨道上
猜你喜欢
  • 1970-01-01
  • 2014-10-31
  • 2021-06-29
  • 2021-11-12
  • 2020-09-20
  • 1970-01-01
  • 2022-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多