简体   繁体   中英

Java String Comparison

The following code is a part of my program

    String [] currency = { "Euro" , "USD" , "Pound" };
private JComboBox
C1 = new JComboBox(currency),
C2 = new JComboBox(currency);
String s,r;
double i,j =0,k=0;

................

private ActionListener d = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object obj = C2.getSelectedItem();

r = "" + obj;
st.setText(r);
System.out.println(r);
System.out.println(currency[0]);

if (r == currency[0])
{

k=1;
}

if (r == currency[1])
{
k = 1.161;
}

if (r == currency[2])
{
k= 0.954;
}
System.out.println(k);
}
};

when r is printed the output is good same case for the printing of currency[0]. The problem is that k is always seen as 0.00. I think it has to do with the comparison of the strings.

Thanks.

Use equals for string comparison Eg, "string".equals("other string"); or in your case

r.equals(currency[0])

When using == on objects you are only comparing references (ie, memory location, not actual content equality).

You might also be interested in using Enums for your currency sample.

compare the two strings by

r.equals(currency[0])

or

r.equalsIgnoreCase(currency[0])

when you don't care about the case of the characters (uppercase or lowercase)

You should use equals for string comparison, and remember to put the string that is not null first:

"Hello".equals(myString)

or in your case:

r.equals(currency[0])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM