0

I have a loop to check the values in an array and compare them to the value in a Combo box. For some reason, even when they match, a compare does not evaluate to true.

Here is the loop, with System output added for troubleshooting:

System.out.println("Race Changed, setting new attribute min/maxes");
                int raceIndex = -1;

                for (int i=0;i<5;i++){
                    System.out.println("RaceCheck index i="
                                      + Integer.toString(i)
                                      + " raceIndex="
                                      + Integer.toString(raceIndex)
                                      + " miscData.raceData[i].raceName="
                                      + miscData.raceData[i].raceName 
                                      + " cboRace.getValue()=" 
                                      + cboRace.getValue()
                                      + " match found="
                                      + (miscData.raceData[i].raceName == cboRace.getValue()));
                    System.out.println("|"+miscData.raceData[i].raceName+"|");
                    System.out.println("|"+cboRace.getValue()+"|");
                    if (miscData.raceData[i].raceName == cboRace.getValue()) {
                        raceIndex = i;
                    }       
                }

                if (raceIndex < 0) {
                    // race was not found, default to Human
                    System.out.println("Race " + cboRace.getValue() + " was not found in racedata");
                    raceIndex = 0;
                }

And here is the output:

Race Changed, setting new attribute min/maxes
RaceCheck index i=0 raceIndex=-1 miscData.raceData[i].raceName=Human cboRace.getValue()=Dwarf match found=false
|Human|
|Dwarf|
RaceCheck index i=1 raceIndex=-1 miscData.raceData[i].raceName=Elf cboRace.getValue()=Dwarf match found=false
|Elf|
|Dwarf|
RaceCheck index i=2 raceIndex=-1 miscData.raceData[i].raceName=Dwarf cboRace.getValue()=Dwarf match found=false
|Dwarf|
|Dwarf|
RaceCheck index i=3 raceIndex=-1 miscData.raceData[i].raceName=Ork cboRace.getValue()=Dwarf match found=false
|Ork|
|Dwarf|
RaceCheck index i=4 raceIndex=-1 miscData.raceData[i].raceName=Troll cboRace.getValue()=Dwarf match found=false
|Troll|
|Dwarf|
Race Dwarf was not found in racedata

I am using Java 7 Update 40, with JavaFX for the combo box. How can I get the matching values to evaluate to true when comparing them?

4

1 回答 1

2

在 Java 中(在 JavaFX 中也是如此)Object应该将 s 与.equals()方法而不是==运算符进行比较。==运算符通过引用比较对象,实际上是通过它们的内存地址。因为Strings 也是对象,所以使用

if (miscData.raceData[i].raceName.equals(cboRace.getValue())) {
    raceIndex = i;
}

参考Java 字符串比较

于 2013-11-13T22:28:16.827 回答