1

I am creating a program that allows you to create a pie chart easily. In the method for removing a slice the if statement inside of a for loop doesnt execute and I cant figure out why this happens. Here is the removeSlice method:

public void removeSlice(Color color, float size, String displayText){
        int num = 0;
        System.out.println("Thing: " + color + " " + size + " " + displayText);
        for(int i = 0; i < slice.size(); i++){
            System.out.println("I: " + slice.get(i).color + " " + slice.get(i).size + " " + slice.get(i).text + " Current: " + i);
            if(slice.get(i).color == color && slice.get(i).size == size && slice.get(i).text.equals(displayText)){
                num = i;
                System.out.println("It Works");
            }
        }
        System.out.println(num);
        slice.remove(slice.get(num));
        totalSize -= size;
        --current;
    }

When trying to remove a slice the console output shows this

Thing: java.awt.Color[r=255,g=255,b=255] 100.0 Hey
I: java.awt.Color[r=0,g=0,b=0] 500.0 Hi Current: 0
I: java.awt.Color[r=255,g=153,b=153] 70.0 Hello Current: 1
I: java.awt.Color[r=255,g=255,b=255] 100.0 Hey Current: 2
I: java.awt.Color[r=153,g=153,b=0] 120.0 Hola Current: 3
0

as you see all of the values equal position 2's values in the ArrayList but still the if statement doesn't execute.

4

7 に答える 7

2

slice.get(i).color == colorに変更する 必要があります slice.get(i).color.equals(color)

メソッドを使用.equals()して色オブジェクトを比較する必要があります。

if(slice.get(i).color.equals(color) && slice.get(i).size == size && slice.get(i).text.equals(displayText)){
                num = i;
                System.out.println("It Works");
            }
于 2013-10-08T14:34:23.637 に答える
1

Color の == 問題に加えて、float の正確な等価比較で問題が発生する可能性があります。比較される値がまったく同じ計算によって生成された場合、または関連するすべての計算が正確である場合に機能します。そうでない場合は、異なる丸め誤差が発生し、実数演算で等しくなる値に非常に小さな差が生じる可能性があります。

100.0 などの小さな整数値の浮動小数点数は整数を正確に表しているため、おそらく現在の問題ではありませんが、異なる数値で問題が発生する可能性があります。

于 2013-10-08T14:39:21.797 に答える
0

異なる値を「equals」で比較してみてください。「==」で比較してみてください。

于 2013-10-08T14:35:29.917 に答える
0

Color オブジェクトには == の代わりに equals() を使用する必要があります。

于 2013-10-08T14:35:33.853 に答える