Two Laptop Bag
The moose likes Beginning Java and the fly likes compare two strings using compareTo Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "compare two strings using compareTo" Watch "compare two strings using compareTo" New topic

compare two strings using compareTo

Alireza Bahmanpour

Joined: Oct 24, 2007
Posts: 23
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

Joined: Jul 08, 2003
Posts: 24199

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"..."

[Jess in Action][AskingGoodQuestions]
Alireza Bahmanpour

Joined: Oct 24, 2007
Posts: 23
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 ]
I agree. Here's the link:
subject: compare two strings using compareTo
It's not a secret anymore!