'If' Statement Failing Check Involving String Array [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm trying to create a program in Java which allows the user to pick from a list of coffees contained in a String array and continues on, but it fails the check and prints out the else statement.
Here is the relevant code:
Scanner scan = new Scanner(System.in);
String[] flavors = {"Black", "French Vanilla", "Hazelnut", "Mango", "Cherokee", "anarcho-syndicalism", "Otis" };
...
System.out.println("Today we have " + Arrays.toString(flavors));
System.out.println("Please enter the name of the coffee you would like exactly as shown above: ");
String coffee = scan.next();
...
for (int i = 0; i < flavors.length; i++) {
if (coffee == flavors[i]) {
String selection = flavors[i];
Though not shown here, I believe everything's properly formatted later on in the program. Any ideas?

In general, when comparing objects for equality in java, use .equals(). Use == for comparing primitives. In java, Strings are objects.
change:
if (coffee == flavors[i]) {
to:
if (coffee.equals(flavors[i])) {
When comparing objects with ==, they will only be equal if they are in fact the same instance.

Related

Why is my code executing both 'IF' and 'ELSE' with '==' but not with '.equals'? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
Java newbie here, I'm experimenting with some simple code using NetBeans. The program simply takes in a few strings into an Array of a predetermined length, while not allowing the previously used ones to be added.
String[] AnArray = new String[3];
for (int i=0; i<AnArray.length; i++) {
System.out.println("Insert a string:");
Scanner s = new Scanner(System.in);
String astring = s.next();
for (String AnArray1 : AnArray) {
if (astring.equals(AnArray1)) { /* THIS IS WHERE I CHANGE astring.equals(AnArray1) TO astring == AnArray1 */
System.out.println ("String already used");
break;
}
else
AnArray[i] = astring;
}
}
for (String AnArray1 : AnArray) {
System.out.println(AnArray1);
}
If the string was already used, it should print out a message "String already used" and not add it, leaving the field empty (null).
If I use .equals, it works correctly (well, as I expect it to).
However, if I use '==' it prints out the message, but still adds the (already used) string to the Array.
Note: All advice is appreciated, but I'd be most grateful for an explanation as to HOW/WHY this IS happening (as opposed to what I should do to improve my code).
EDIT: I don't see how this is a duplicate. If someone can paste the relevant part of the answer to my question, I would be grateful. My question is: since the condition is True in BOTH cases (using == or .equals) why does the .equals() follow the break command while == triggers else AS IF it's ALSO false?
I hope the below summary helps you in your case:
use == to compare primitive e.g. boolean, int, char etc, while
use equals() to compare objects in Java.
== return true if two reference are of same object. Result of
equals() method depends on overridden implementation.
For comparing String use equals() instead of == equality
operator.
In Java, == compares the object's references, not the object's contents. That is, with == you check whether the two references point to the same object in memory (which implies that they also have the same contents). With .equals(), however, you check whether the contents of the objects, i.e. the string characters, are the same. Also see e.g. What is the difference between == and equals() in Java?.
Edit: Here's a working example that tries to stick as close to your original code as possible:
String[] AnArray = new String[3];
for (int i=0; i<AnArray.length; i++) {
System.out.println("Insert a string:");
Scanner s = new Scanner(System.in);
String astring = s.next();
boolean alreadyContains = false;
for (int k=0; k<i; k++) {
AnArray1 = AnArray[k];
if (astring.equals(AnArray1)) {
alreadyContains = true;
break;
}
}
if (alreadyContains) {
System.out.println ("String already used");
} else {
AnArray[i] = astring;
}
}
for (String AnArray1 : AnArray) {
System.out.println(AnArray1);
}

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.

Get String from command line → split string → if/else if statement returning else statement for no reason [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
(Sorry for the weird title, but I can't figure out what actually the problem is)
The following code should get a String from the command line first (which works), then the input is being splitted (works perfectly, too; I checked by printing both Strings before the if/else as you can see in the part I commented out again) and then it should check what the first part of the splitted String is. And for example if it equals "tweet" it should procedure with the Tweet method.
But somehow it doesn't get that right. It always executes the else statement...
Scanner sc = new Scanner(System.in);
System.out.print("> ");
String input = sc.nextLine();
String[] splitString = input.split(" ");
if(splitString.length != 2){ throw new IllegalArgumentException(); }
String command = splitString[0];
String value = splitString[1];
/*System.out.print(command);
System.out.print(value);*/
if(command == "tweet") { Tweet(value); }
else if(command == "help") { ShowHelp(); }
else { System.out.println("Command "+command+" not found."); }
I tried entering "tweet asdf", but it returns
> tweet asdf
Command tweet not found.
What did I do wrong? I'm confused D:
Use the .equals method instead of ==.
== compares the references. .equals will compare the actual content of the two strings.
When comparing strings, you will almost always want to use .equals not == as usually you are wanting to compare content, not reference.
You're using == to compare two objects. This compares their references. Use if(command.equals("tweet")) instead to compare by values.
Due to string interning depending on the JVM and implementation(official classpath, GNU classpath, etc) your approach may operate properly hit-or-miss.

If statement wont recognize string [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have an if statement that takes a string, and if another string has the same value as that string do 1 thing, and if the variable doesnt equal that string do another thring
here is my code
if(Pos != "D"){
System.out.println("doesnt = D");
}
if (Pos == "D" ){//WHY ISNT THIS WORKING
System.out.println("it does = D");
}
It recognizes when the variable doesnt = D and prints "doesnt = d" but when the variable = D it does nothing. I dont know why.
thanks
Never compare Strings with == or != since these check to see if two String variables refer to the same object reference, and this is not what you're interested in. Instead use the equals(...) or equalsIgnoreCase(...) method to see if the two Strings have the same chars in the same order as that's what really matters here. i.e.,
Use equals to compare strings :
if ("D".equals(Pos))

Categories