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

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.

Related

How to use input to get a particular element in a list? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I'm new to Java/programming and I'm trying to write a simple program that gets an element from a list IF that element is equal to some user input. I'm using a for-loop and if-statement to achieve this but even though the user input and element matches up the programming won't print the element to screen. If someone could explain why this is not working it would be very appreciated. Cheers
public static void main(String[] args){
ArrayList<String> names = new ArrayList<String>();
String tempObject;
String findName;
names.add("John");
names.add("Ronny");
names.add("Gona");
names.add("Gina");
Scanner Input = new Scanner(System.in);
System.out.print("Search list for: ");
findName = Input.nextLine();
for (int i = 0; i < names.size(); i++){
tempObject = names.get(i);
if (tempObject == findName){
System.out.print("\n" + tempObject);
}
}
}
Here you go:
if (tempObject.equals(findName)){
System.out.print("\n" + tempObject);
}
For objects, which String is, always use method equals(), since == will compare references, not values (or what is set in equals() method - in String, it will compare the size, and then compare each char on the same place if they are equal - also, if you need, you have a method called equalsIgnoreCase - sometimes, its better to use that for user inputs).
For primitives, you will have to use ==.
There is difference between equality and identity, in your code above you used identity instead of equality, if you change your code (to use equality) as the below you will get what you need
if (tempObject.equal(findName)){
System.out.print("\n" + tempObject);
}
You should use String equals to compare two Strings for equality, not operator == which just compares the references.
Try the if statement like this:
if (tempObject.equals(findName)){...}

Why does "T" not equal "T" in this example? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm trying to write a simple hangman game in java for my college class. For some reason the if statement never returns seems to think that the two substrings being compared are equal. The two print statements show that by all rights the two should equate.
public String guessLetter(String letter)
{
String blanks = "";
String theWord="FOO";
for(int i=0; i<=theWord.length()-1; i++)
{
System.out.print(letter.substring(0,1).toUpperCase());
System.out.print(theWord.substring(i,i+1)+ "\n");
if((letter.substring(0,1).toUpperCase())==(theWord.substring(i,i+1)))
{
blanks = blanks + theWord.substring(i,i+1);
}
else
{
blanks = blanks + "___ ";
}
}
return blanks;
}
EDIT - As a great many people have pointed out, when comparing Strings, one must use the equals method instead of ==. I was unaware.
You are comparing a String so use "String".equals() dont use ==
use like this:
if((letter.substring(0,1).toUpperCase()).equals(theWord.substring(i,i+1)))
Java dont have == for string
you must use string1.equals(string2) function
if((letter.substring(0,1).toUpperCase())==(theWord.substring(i,i+1))) \ this is wrong for strings
When you compare strings you should use .equals or .equalsIgnorecase
if((letter.substring(0,1).toUpperCase()).equals(theWord.substring(i,i+1)))
ans also checkout the difference between == and .equals in java good explanation is given there.

How to compare multiple strings? [duplicate]

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.

Java Scanner: That looks easy [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
Well, I really tried to solve (and google) it, but I couldn't.
And sorry for my english and for that idiotic title (This one is the best that came to mind) :)
System.out.println("AM I A GENIUS?");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
if (s == "yes"){
System.out.println("^_^");
}
else{
System.out.println("I am not a genius(");
}
console:
AM I A GENIUS?
yes
I am not a genius(
if (s == "yes") --->> NEVER
instead use
if (s.equals("yes"))
EDIT: just for explain: the first statement is a boolean operator that controls if the references of the object s and the object "yes" are the same.
the second one compares the real content of the String variable.
So, in general, you should never use boolean comparison when using not primitive types.
In fact, you are comparing references and not the 2 String objects.
What you should do is the following:
System.out.println("AM I A GENIUS?");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
if (s.equals("yes")){
System.out.println("^_^");
}
else{
System.out.println("I am not a genius(");
}
The equals method of the class String now compares the Strings s and "yes" characterwise.
I think Roman was right, you should be using .equalsnot ==, they imply different things.
== checks the references to the objects, which can work depending on what what you're comparing, but it's best to use .equals() which compares the content of the strings.
Your code should look like this:
String s = scan.nextLine();
if (s.quals("yes")){
System.out.println("^_^");
}
else{
System.out.println("I am not a genius(");
}
I'd also recommend using a .toLowerCase() on the user input, because that also cause the conditional to return false when the user types "Yes" as supposed to "yes". That would look like: s=s.toLowerCase();
Hope this helps.

My program is ignoring my if statement and goes straight to the else [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
String firstanswer = scan.nextLine();
if(firstanswer == answer2)
{
System.out.println("OK lets get started");
}
else
{
System.out.println("That is incorrect, of course you want to play");
}
//answer2 is set to "yes", i declared it above
make it firstanswer.equals(answer2) instead of firstanswer == answer2.
When you want to check for equality of String in java then use equals method instead of == operator.
equals method checks whether the contents of String objects are same
== operator checks whether both the reference variables refer to same String object
To understand about strings and equality, read String comparison with equals and assignment operator It will help you understand the concept well.
Use equals() instead of == to compare strings.
if(firstanswer.equals(answer2)) is what you're looking for.
firstanswer and answer2 are pointers to string objects. == checks to see whether the pointers are equal (whether they point to the same object), while equals() compares the contents of the two strings and returns a boolean representing whether or not the contents are equal.

Categories