Home arrow static arrow Java Programming [Archive] - How to compare with C:\\
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - How to compare with C:\\
This topic has 4 replies on 1 page.

Posts:5
Registered: 7/28/04
How to compare with C:\\  
Aug 3, 2004 2:23 AM



 
Hi,

I've got a text field containing a path to the local hd and I want to check if the path is "C:\" if that is the case I pop a message saying it's an invalid path.

Problem seems to be I have to type "C:
" in the java code to compare with the "C:\" of the text field...tried equalsTo(), compareToIgnoreCase() and a regular == comparison. No luck.

Snippet:
[CODE]if (path.getText() == "C:
")[/CODE]

If anyone got a tip on how to solve this I'd appreciate it. Thank you

/G

 

Posts:11,200
Registered: 7/22/99
Re: How to compare with C:\\  
Aug 3, 2004 2:28 AM (reply 1 of 4)



 
You need to use either the equals or the equalsIgnoreCase method. There is no "equalsTo()" method, and the == -operator compares object identity, not object value.
if (path.getText().equals("C:
"))
If the equals method does not work the text in the text field is not what you think it is.
 

Posts:5
Registered: 7/28/04
Re: How to compare with C:\\  
Aug 3, 2004 2:37 AM (reply 2 of 4)



 
Thank you jsalonen,

You are right, I was quite confused that the .equals() didn't work as I had expected it to, indeed the text in the textfields wasn't what I thought it was.

The text was picked up from a file and adding .trim() to the fetch clauses cleaned up the text and it does now actually equal to c:
. The problem seems to have been trailing carriage returns and linefeeds.

So visually it was the same, but not according to the function :)
 

Posts:3,183
Registered: 10.09.03
Re: How to compare with C:\\  
Aug 3, 2004 2:39 AM (reply 3 of 4)



 
One additional tip would be to learn where to find this kind of information. Google is your friend, but you could also look it up in the javadocs:

http://java.sun.com/j2se/1.4.2/docs/api/

Or to be more precise, the String class:

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html
 

Posts:11,200
Registered: 7/22/99
Re: How to compare with C:\\  
Aug 3, 2004 2:56 AM (reply 4 of 4)



 
And since you are comparing the equality of two file paths you should rather use the java.io.File class than Strings..
File croot = new File("c:/");if (new File(textfield.getText()).equals(croot))
This way you don't have to worry about whether the system where your program is currently run is case sensitive or not, c:\ and C:\ are the same on windows..
 
This topic has 4 replies on 1 page.