• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

compare two strings using compareTo

 
Alireza Bahmanpour
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I have a little problem with the compareTo method. I want to compare two strings, and if they are not equal to each other, I want it to recurse with a new input from the user. I'm not sure about how to say if 'two strings are not equal to each other'. Do I use !=0 or <>0.

Here is my code:


This code does not work, but if I put <0, the first condition ("open") will get evaluated, and the second one won't.
Thanks in advance
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem here is that it will ALWAYS be the case that either the first or the second condition is not true -- the String can't both be "open" and "closed" at the same time, right? -- s instead of "or" (||) you want "and" (&&); i.e., you want to say "if the String is not "open" and it's not "closed", then..."

Furthermore, while "compareTo" is very useful in situations where you want to sort Strings into alphabetical order, if all you're doing is comparing them for equality, use "equals()" instead; it's more concise, and probably more efficient. Then you can use the "not" (!) operator to mean "not equals", which reads very nicely.

So altogether,

if(!requestStatus.equals("open") && !requestStatus.equals("closed")){

If you like, you could say

if (! (requestStatus.equals("open") || requestStatus.equals("closed")) {

which reads "if requestStatus is not "open" or "closed"..."
 
Alireza Bahmanpour
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot, it's now working.
I actually tried a similar thing, but I just made a simple mistake, which was to put brackets around both conditions. Something like this:
if(!(requestStatus.equals("open")) || !(requestStatus.equals("closed"))){

Thanks again
[ March 16, 2008: Message edited by: Alireza Bahmanpour ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic