This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
UPDATE:
Thank you all for your answers, especially pertaining to .equals().
The only detail is that the "msgCode = ..." and "msgValue = ..." statements are enough to return an empty stirngBuilder. I.e., I don't even have to declare the IF statement to make it stop working.
Any clues?
ORIGINAL:
Please let me know why StringBuilder returns nothing (perhaps doesn't even work) when I include the rest of the code (besides stringBuilder.append(...)) inside the while().
When I include just stringBuilder.append(...), then there is a return value.
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString + "\n");
// analyze the first 3 characters in the message
String msgCode = receiveString.substring(0, 3);
Number msgValue = Integer.parseInt(receiveString.substring(4, receiveString.length()-4));
// use IF-ELSE since SWITCH doesn't work with String
if (msgCode=="ATT") {
dataATT[2*dataATTcount+1] = msgValue;
dataATTcount++;
} else {
dataMED[2*dataMEDcount+1] = msgValue;
dataMEDcount++;
}
}
Thanks
use
msgCode.equals("ATT")
instead of
msgCode=="ATT"
with '==' you compare the references of the string and not the string itself.
Never-ever use == for Java string comparison. Use equals().
P.S. Okay, there might be some cases where == would be suitable. But for the vast majority of situations, equals() is the way to go.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I am a beginner in android studio. I am working on a quiz app . The app should check for two strings to be compared and give the correct answer. But comparing the two strings (even though if they are same) is not giving the correct output. Instead it is directly going to the final return statement in the code. Here’s the code:
// ...
EditText Answer1 = (EditText) findViewById(R.id.answer1);
String ans = Answer1.getText().toString();
Log.v("MainActivity", "City name :" + ans);
String answer= String.valueOf(Answer1);
// ...
public String YourAnswers(String ans, boolean isDT, boolean isHC, boolean isBO,String answer) {
String Message = "1.:You answered \n"+ans+ "\n" +ques1(answer);
Message = Message + " \n 2.: \n" +question2(isDT,isHC,isBO) ;
return Message;
}
public String ques1(String answer) {
if (answer == "Jefferson City"){//||ans=="Jeff City"||ans=="Jeffcity"||ans=="Jeffersoncity"){
return "correct";
}
else if(answer =="Jeff City") {
return "correct.";
}
else if(answer =="Jeffcity"){
return "correct..";
}
else if(answer.equals("Jeffersoncity")){
return "correct.....";
}
return "Sorry,but the correct ans is Jefferson City";
}
When it enters into ques1(), it is directly going to the last statement i.e. return "Sorry,but the correct ans is Jefferson City";. When I enter the correct answer too it is returning the above mentioned line.
Any ideas as to why this might be happening?
"==" is not the correct way to compare contents of a String in java.
use string1.equals(string2)
Use .equals() throughout instead of ==.
However try this code to allow for any capitalization of answer using toLowerCase():
import java.util.Arrays;
...
...
String[] answers = {"jefferson city","jeff city", "jeffcity", "jeffersoncity"};
if(Arrays.asList(answers).contains(answer.toLowerCase())) {
return "Correct";
} else {
return "Sorry,but the correct ans is Jefferson City";
}
Background
There are two common methods used in order to compare two strings in Java. In your example, rather than making use of one of them, you’re using == which is an equality operator—these, you can’t use to check for equality on Strings.
The first method you may use is equals, located on the String. This will check and see if all characters contained by the String are exactly the same—that is, it also makes sure the String you’re giving it has the same letter case as the one you’re comparing it to.
Here’s an example:
"Hello, world!".equals("Hello, world!"); // ‘equals’ returns true
"Hello, world!".equalsIgnoreCase("hello, world!"); // ‘equals’ returns false
The second method you may use is equalsIgnoreCase, also located on the String. This will return true if the Strings compared are the same, but don’t give into account if they’re of different cases—it doesn’t care.
Let’s repeat the previous example and see what happens:
"Hello, world!".equals("Hello, world!"); // ‘equals’ returns true
"Hello, world!".equalsIgnoreCase("hello, world!"); // ‘equals’ returns true
See how both returned true this time around?
Solution
With all this in mind, we can go ahead and fix your code up:
public String ques1(String answer)
{
if (answer.equals("Jefferson City"))
{
return "correct";
}
else if(answer.equals("Jeff City"))
{
return "correct.";
}
else if(answer.equals("Jeffcity"))
{
return "correct..";
}
else if(answer.equals("Jeffersoncity"))
{
return "correct.....";
}
return "Sorry,but the correct ans is Jefferson City";
}
That’s going to work just great!
Moreover
That I put { on new lines doesn’t affect the outcome of your program. There are however good reasons as to why you’d want to put them on separate lines. The reason I’m writing this is because I’m highly fond of bringing up the debate all over again—making people mad.
Use .equalsIgnoreCase on Strings if not case sensitive. Also to avoid nullpointer exception use the following syntax
"Jeff City".equals(stringVar);
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
First off, I know this might have been answered SOMEWHERE but I can't seem to search for the correct terms to get an answer. Also, I'm pretty new to coding, and obvious here, so this probably won't be the best written 'question'.
Quick backstory: I'm coding a sorting game in BlueJ(I know... shitty, but it's what we are learning in school), and for a method I'm creating for any yes/no questions I need isn't working properly. At first, I was having an issue with it allowing to to have the user input save as a String, now I'm having an issue with that String used in the if-else statement parameters. This is what I have right now:
public void userAnswer(int method) //used for yes/no questions
{
System.out.println("Please type 'y' for yes and 'n' for no.");
String answer = keyboard.next();
answer.toLowerCase();
System.out.println(answer + "worked");
if(answer == "y")
{
System.out.println("worked2");
if(method == 0)
completeOrNot();
if(method == 1)
usersMove(theArray);
}
else if(answer == "n")
{
System.out.println("worked3");
System.out.print("\n");
}
}
I'm completely stuck as to why it's not moving into the if-else statement. I test to see if it would print the String, and it will, but it won't convert it to lower case. I just don't know what to do. Any and all help would be appreciated!
When comparing Strings in Java, use the equals() method. Otherwise, you compare their memory locations if you use ==.
"hi".equals("hello") returns False
"hello".equals("hello") returns True
Don't use == to compare strings. use equals:
answer.equals("y")
Strings in Java are objects - you need to evaluate with the equals method for equality, not the == operator for reference identity:
if ("y".equals(answer)) {
// code
} else if ("n".equals(answer)) {
// code
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I don't understand what's wrong with the IndexOf function ???
public String[] PseudoExisteTest() {
// looking if an XML tag contain "OK"
String exampleText = "<result>OK</result>";
int ind1;
int ind2;
String returnTable[] = new String[4];
String tag="result";
String textresult;
ind1=exampleText.indexOf("<"+tag+">"); // 0
ind2=exampleText.indexOf("</"+tag+">"); // 10
textresult=exampleText.substring(ind1+tag.length()+2, ind2);
if ((textresult=="OK")) { // YES => Normally we pass here (="OK") !
returnTable[0]="It'OK";
}
else {
returnTable[0]="Not, value is : "+textresult+"!"; // Not, value is : OK !!! ?????
}
returnTable[1]="blabla";
return returnTable;
}
The value is "OK" but on the condition, that's don't works well ????
Is anybody can help me ?
Thanks in advance.
The problem is that you're using == to do a comparison of Java Strings. For objects in Java, which includes Strings, == tests whether the objects are the same. Instead, say textresult.equals("OK") or textresult.equalsIgnoreCase("OK").
As the comments say, see also How do I compare strings in Java?
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have two JTextFields txf1 and txf2.
In both of them I input the same content (for example: "test").
I made and If statement:
if (txf1.getText() == txf2.getText()) {
System.out.println("Equal");
} else {
System.out.println("Error");
}
Why it prints out the error message? I even made a System.out.println(txf1.getText()) and System.out.println(txf2.getText()) and the same looks equal, but prints out the error message?
String comparison in Java is done using String#equals, using == means you are comparing the memory reference of the objects, which won't always return true when you think it should.
Try something more like....
if (txf1.getText().equals(txf2.getText())) {
...instead
Also you can use this good practice which makes your text box entries efficient.
if (txf1.getText().trim().equals(txf2.getText().trim())) {
Use the equals method to compare Strings. == only compares the object reference. equals compares the actual content of the Strings.
Your code should be something like this:
if (txf1.getText().equals(txf2.getText())) {
System.out.println("Equal");
} else {
System.out.println("Error");
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
comparison of two Strings doesn't work in android [duplicate]
(4 answers)
Closed 9 years ago.
I am working on a login page in an Android App.
As you know, the app must check if the username and password are valid, and then grant the user access to the application.
I have used the following code:
...
EditText un = (EditText) findViewById(R.id.username1);
EditText pw = (EditText) findViewById(R.id.password1);
String u = un.getText().toString();
String p = pw.getText().toString();
String myUser = "user1";
String myPass = "pass1";
//////// Now on the click of the Login Button:
public void onClickL (View view){
if ( (u == myUser) && (p == myPass)) /////// move to a new activity
else ///////Display a warning message: Try again
}
I entered the correct strings in both editText fields, however i always get the warning message.
I don't understand what is wrong with it.
Please help :)
You should use the equals() method of the String class to compare Strings. The == comparison only compares object references.
if (p.equals("Password")) {
//Do stuff
}
So what you have should be changed to:
if ((u.equals(myUser)) && (p.equals(myPass))) {
// do stuff
}
See here for a lot more information about this often-mixed-up topic: How do I compare strings in Java?
== will do an object comparison between the strings in this situation, and although the value may be the same of the String objects, the objects are not the same. Hence why we use String.equals(string); to compare the value of two string objects.
So
if(u.equals(string)) and p.equal(string)are probably what you are looking for.
Always use String.equals(string) to compare strings. == will compare if the references are equal which doesn't work the way you want for strings.
Since java doesn't have a few modern features, == does not work on strings. Instead, it is a little more complicated.
To check if two string are equal, in the if statement put:
String.equals(otherString)
To compare lengths, use the .length method to compare them, and you could use ==.
Thanks.