How to compare multiple strings? [duplicate] - java

This question already has answers here:
String.equals() with multiple conditions (and one action on result) [duplicate]
(7 answers)
Closed 2 years ago.
I was wondering how I can compare multiple strings in one line. I tried using the || but it doesn't work for booleans or strings. this is what my code is like:
}else if(question != "a" || "b") {
System.out.println("Sorry that isn't an A or a B");
For those who marked it duplicate, I checked over 200 questions here on stack overflow, and none worked. The one #Chrylis posted actually didn't help. they were just asking about the difference in == and .equals()

First of all, don't use == for strings. You'll learn why later. You want to compare strings by their contents, not where they are in memory. In rare cases a string of "a" could compare false to another string called "a".
Second, split it up so you are performing boolean logic on the comparison results:
else if(!(question.equals("a") || question.equals("b")) {

You can try using Arrays.asList():
else if (!Arrays.asList("a", "b").contains(question)) {
...
}

Two things wrong: You can't just specify multiple values with || (or &&) like that. You need to specify both the left side and the right side explicitly each time.
Second, use equals to compare String values, not the == (or in this case !=) operators. == compares two object references to see if they are the same object.
} else if (!("a".equals(question) || "b".equals(question)))
Or an alternative is to make a temporary List and use contains, which might be clearer for longer lists of things to test:
} else if (!Arrays.asList("a", "b").contains(question))

String[] options = {"a", "b"}; // Must be sorted.
if (java.util.Arrays.binarySearch(options, question) < 0) {
System.out.println("Sorry that isn't an A or a B");
}
Alternatively (assuming your strings don't contain |:
if ("a|b".indexOf(question) == -1) {
System.out.println("Sorry that isn't an A or a B");
}

As an aside, you should use equals for objects not ==
To answer your question, you have to repeat the equals call on both sides of the ||
}else if( ! (question.equals("a") || question.equals("b")) ) {

}else if( !(question.equals("a") || question.equals("b")) {
System.out.println("Sorry that isn't an A or a B");
You can't do NOT equals a OR b
You have to do NOT(equals a OR equals b)
Secondly, you are comparing strings with !=, but you should be comparing strings using the .equals(String) method. This has been said millions of times, but: == and != are comparing object references, whereas .equals(String) is comparing String values.

Related

How do you check if a string is not equal to an object? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I ave a code where I want to use != sign. But since I am using String, How do I not equals Sign. Hers is my code. So I want all this statement not to equal to each other so it can print Tie Game.
if (Array[0] == Array[currentPlayer] && Array [1] ==
Array[currentPlayer] && !Array [2] == Array[currentPlayer])
The above code is when everything equals to each other. But I want this statements not to equal each other.
Keep in mind that I have not used Int or Char, I am using String.
For string inequality, negate a call to the equals method using the !:
String x = "ABC";
String y = "XYZ";
if(!x.equals(y)) {
//do stuff
}
! can be used to negate ANY boolean expression, and String.equals returns a boolean.
You can do something like:
if (!Array[0].equals(Array[currentPlayer]) && !Array[1].equals(Array[currentPlayer])
&& Array[2].equals(Array[currentPlayer]))
Use equals() if you want case sensitive match meaning it will look at case of string as well when matching.
If you want case insensitive matching you can use equalsIgnoreCase() method in place of equals()

Do while loop comparing Strings

I'm trying to do a "do while" loop with a nested if statement. I'm trying to compare two possible values for a String variable "word". If !word.equals "deeppan or thin" do something, else do something. But its not liking me using the or || comparator .. Any suggestions would be welcome.
do {
word = scan.next();
if ( !word.equalsIgnoreCase( "Deeppan" || "thin" ) ) {
System.out.print("Sorry you must specify a Deeppan or thin base, try again: ");
} else {
break;
}
} while ( true );
equalsIgnoreCase takes a single string argument, not a logical expression. You can combine them with || or && though:
if (!word.equalsIgnoreCase( "Deeppan") && !word.equalsIgnoreCase("thin" ))
You have to do it like this:
if (!word.equalsIgnoreCase("Deeppan") && !word.equalsIgnoreCase("thin")) {
Think about the || which i switched to &&, because the if should only be true, if the value is not the first AND not the second one!
This part is wrong, that's not how you use the boolean || operator, and anyway the logic is incorrect:
if (!word.equalsIgnoreCase("Deeppan" || "thin"))
It should be like this, comparison-operator-comparison, and notice the correct way to state the comparison for the effect you want to achieve:
if (!(word.equalsIgnoreCase("Deeppan") || word.equalsIgnoreCase("thin")))
Or equivalently, using De Morgan's laws (and easier to read and understand, IMHO):
if (!word.equalsIgnoreCase("Deeppan") && !word.equalsIgnoreCase("thin"))
You have a few issues going on. First:
"Deeppan" || "thin"
is attempting to use the boolean "OR" operator to compare two strings. The "OR" operator can only compare boolean results and returns a boolean that is the result of the comparison:
System.currentTimeMillis() == 123455667 || object.equals(this) // both sides are boolean results.
true || false // returns 'false'
But let's pretend for a second that "Deeppan" || "thin" is OK (remember, it isn't) and the compiler knows that you want to compare the two strings. It still leaves the issue that the OR operator returns a boolean result (true or false), which you are then attempting to pass into the method equalsIgnoreCase on the word variable. equalsIgnoreCase takes a String argument, not a boolean. This is the second compilation issue. As has been pointed out, what you need is to check for the conditions separately and OR the result to get the final boolean
if("Deeppan".equalsIgnoreCase(word) || "thin".equalsIgnoreCase(word)) {
// do something
}
("Deeppan" || "thin")
is a boolean expression. equalisIgnoreCase takes a string. Therefore you need to make two seperate calls and OR the (boolean) results

Java if statement equality [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
How can it be possible, that If statement doesn't understand two equal things that they are the same?
Situation:
I write into txfName field only letter b and then push button "Ok".
Code:
String letter = "b";
boolean same = false;
if (letter == txfName.getText()) {
same == true;
}
After if statement program shows me that variable same is false. Why? How can it be possible?
If I write code like this:
String letter = "b";
boolean same = false;
if (letter == "b") {
same == true;
}
Then after if statement program shows me that variable same is true. I don't understand, how it can be possible.
== compares to see if two objects are the same. When you are dealing with strings they are objects, so they may not have the same reference event though they can have the same value. You want to use .equals() instead.
For more details, Strings are special in java, as there are some internal workings that have a String pool. So in some cases the == may actually seem to be working, but in other cases it may not be. The reason is the String pool tries to cache recently used Strings to reduce the memory overhead. Anyway .equals() is what you are looking for.
for your first question
String letter = "b";
boolean same = false;
if (letter.equals( txfName.getText())) {
same = true;
}
return same;
will return true if txfName.getText() returns "b"
To compare objects in java use .equals() method instead of "==" operator
Replace the following code
if (letter == txfName.getText())
to
if (letter.equals(txfName.getText()))

How to use the while statement for text [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm trying to make a simplified version of Black Jack in Java using eclipse. I'm trying to make it so the player types 'hit' or 'stand', and while they haven't, it keeps prompting them to do so.
while (hitorstand != ("hit") || hitorstand != ("stand"))
{
System.out.println("Would you like to hit or stand?(1 for hit, 2 for stand)");
hitorstand = scan.nextLine();
hitorstand.toLowerCase();
}
if (hitorstand.equals("hit"))
{
playercard3 = random.nextInt(10) +2;
System.out.println(""+playercard3);
}
else if (hitorstand.equals("stand"))
{
System.out.println("You had a total value of " + playercardtotal + ".");
if (hiddendealercard == card2)
When I run it, no matter what I type it cannot escape the while loop. I know it would work if I used numbers but I really want to learn how to use words as input.
while (hitorstand != ("hit") || hitorstand != ("stand")) // This is not the right way
Use the equals() method for String value comparison. == is for object reference comparison.
while (!hitorstand.equals("hit") || !hitorstand.equals("stand")) // This is
I'm not sure why you'd use the != in the while loop condition, whereas you've properly used (hitorstand.equals("hit")) just below the while, in a if statement.
Also, there seems a minor mistake in the while loop block.
hitorstand.toLowerCase(); // This does nothing
As Strings are immutable in java, you need to assign back the changed string to be able to see the changes
hitorstand = hitorstand.toLowerCase(); // Assigning back the lowercase string back to hitorstand
You need to use .equals(..) instead of ==. This is because == is used for reference equality, while .equals() is simply for value equality.
For example:
while(!hitorstand.equals("hit") || !hitorstand.equals("stand"))
Comparing hitorstand != ("hit") you actually compare object references not the String value itself. To compare strings you need to use equals method. In java every class inherits equals ( from Object ) and it can be overriden for custom object comparison
Try this:
while (!hitorstand.equals("hit") || !hitorstand.equals("stand")){
Adding to the answers, a good rule of thumb is to use .equals() with strings and == with integer values or variables with integer values (or the value null).
One way you could do this would be to use a character. For example: instead of
while (hitorstand != ("hit") || hitorstand != ("stand"))
you could have it check for the first character in the string using the charAt() command with the index of the string in the parenthesis. So since your looking for the first character, it would be at index 0.
while (x != 'h' || x != 's')
x being a char.
Inside your while loop,
System.out.println("Would you like to hit or stand?");
hitorstand = scan.nextLine();
hitorstand.toLowerCase();
x = x.charAt(0); // you would just add this line. This gets the character at index 0 from the string and stores it into x. So if you were to type hit, x would be equal to 'h'.
Your if statement could stay the same or you could also change the condition to (x == 'h') and (x == 's'). That's up to you.

Why don't strings compare as equal? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
String is not equal to string?
I'm new to java and I can't figure out what's wrong with this code block.
I know the array isn't null I'm testing it elsewhere. Maybe there is a syntax problem I'm used to program in c#.
Scanner input = new Scanner(System.in);
System.out.println("Enter ID :");
String employeeId = input.nextLine();
int index = -1;
for(int i = 0 ; i < employeeCounter ; i++)
{
if(employeeId == employeeNumber[i])
{
index = i;
}
}
if(index == -1)
{
System.out.println("Invalid");
return;
}
I always get to the 'Invalid' part. Any idea why ?
Thanks in advance
employeeNumber[0] is "12345"
employeeId is "12345"
but I can,t get into the first if statement although employeeId IS equal to employeeNumber[0].
Don't compare strings with ==.
Use
if (string1.equals("other")) {
// they match
}
Compare strings like that
if(employeeId.equals(employeeNumber[i]) {
}
As others have pointed - full code will be helpful, but my guess would be this line of the code:
if(employeeId == employeeNumber[i])
You don't compare 2 strings by using ==. Use equals() or equalsIgnoreCase() instead. == only checks for object equality i.e. are employeeId and employeeNumber referencing to the same object in memory. So, for objects always use the equals() method..for Strings you can also use equalsIgnoreCase() for a case insensitive match. == should be used on primitive types like int, long etc.
When you use == with two string, it compares pointer addresses
You should use firststring.equals(secondstring) in order to compare two strings
Use equals() method to compare Strings
if(employeeId.equals(employeeNumber[i])){}
When you compare strings, use
String1.equals(String2);
This should give you the result
"==" checks whether the reference for two objects are same. But equals() method checks whether the content is same or different.

Categories