Why is this if-statement not working? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I've been working on a small personal project and mainly polishing the IO aspect of the program.
I'm mainly having trouble with one method, which is responsible of calling two methods that read one line of text document and dissect it to find a certain string.
public boolean noSavedGame(){
boolean noGameFound = false;
read(); //method reads the text document that can have multiple lines
String temp = find(); //method finds the property and returns it in a string
if(temp == "none"){
System.out.println("Saved game not found");
noGameFound = true; //a saved game WAS NOT FOUND
}
else{
System.out.println("saved game found");
noGameFound = false; //a saved game WAS FOUND
propertyDetail = temp;
}
return noGameFound;
}
So, the first line of the text document looks like this:
<pastSavedGame> - none
read() correctly takes that line and find() correctly returns "none" as its supposed to return the property.
But the conditional is not working right. Even though temp equals "none", the if-statement is executed, not the else statement. At first, I thought whitespace was an issue, but does not seem to be a factor.
I apologize for what may be a very simple question, but I am new to Java. Thank you for the help.

To compare strings use equals() instead of ==.
equals() compares the content; == checks whether it is the same instance.

Related

Return is always true, even when it's false [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
I'm trying to make a dutch zipcode validator. On the first step i need to check if the first char of the zipcode (which is always a number), is between 1-9. But when i just tried to make a simple if statement to check if the first char is false, it comes back as true. In this example I took a premade string "2097AR" as input for the method "checkPostcode".
public static boolean checkPostcode(String postcode){
String postcodeEen = postcode.substring(0,1);
boolean resultCheck = true;
System.out.println(postcodeEen);
if (postcodeEen == "1"){
resultCheck = false;
}
return resultCheck;
}
The = operator for strings in Java checks if the two objects are the same, whereas #equals(String s) checks if the contents of the string are the same.
The function always returns true because postcodeEen and "1" aren't the same object, which makes the condition postcodeEen == "1" false.
Here is the working code segment:
if(postcodeEen.equals("1"){
return false;
}

Java's relational operators not working correctly in if-else condition. Android Programming [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
Please check the following code snippet from button's onClick event handler.
The if statement does not execute even though its TRUE (because of relational operators == and && maybe)... but works fine when string method( .contains() ) used as shown at the end.
EditText uname = (EditText)findViewById(2);
EditText pwd = (EditText)findViewById(3);
TextView msg = (TextView)findViewById(4);
String a = uname.getText().toString();
String b = pwd.getText().toString();
if(a==("afnan")&& b==("secret")){
msg.setText("abc");
}else {
msg.setText("xyz " + a + b); // concatenated a and b to see their values and they are same as in IF statement so why does ELSE always get executed but not IF?
}
Replacing relational operators with the following works fine but if statement gets true for "afnanaaaaa" since it does contain "afnan" but not EXACLTY contain "afnan":
if(a.contains("afnan")&& b.contains("secret")){
msg.setText("Welcome !!!");
}else if (a!= "afnan" && b!= "secret"){
msg.setText("xyz ");
}
HELP PLEASE !!!!!!!!!!
You need to understand that Java compare by reference rather than by value in this case. The following code is displays the correct solution:
if(a.equals("afnan")&& b.equals("secret")){
msg.setText("abc");
}else {
msg.setText("xyz " + a + b); // concatenated a and b to see their values and they are same as in IF statement so why does ELSE always get executed but not IF?
}
Ordinary objects for comparison is to use the method equals(). (etc. a.equals(b)) For arrays and some class need static method. You may want to improve basics of Java with the help of books. About it (equals) writes in the early chapters.

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.

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.

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