This topic is now archived and is closed to further replies.


Java: urgent question, String .compareTo keeps returning 2

Recommended Posts

Ive got 2 text fields that i am comparing to see if they have the same data.
if (txtField1.toString().compareTo(txtField2.toString())==0)
JOptionPane.showMessageDialog(null, "They are the same","Result", JOptionPane.INFORMATION_MESSAGE); 
JOptionPane.showMessageDialog(null, "They are not the same,"Result", JOptionPane.INFORMATION_MESSAGE); 
but the compareTo keeps returning 2 now matter what, if they are same or not whats wrong? Thanks, [edited by - johnnyBravo on November 17, 2003 7:37:34 PM]

Share this post

Link to post
Share on other sites
The problem is you are not comparing the text the two textfields contain, but rather a string representation of the textfiled component. Print out the return value of the toString() method to see what I mean.

Rather than using toString(), call the getText() method. This will give you the String that the textfield contains.

Also, are you sure you want to use compareTo? If all you are testing for is equality, you ought to be using Object.equals().


Share this post

Link to post
Share on other sites