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.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
String.equals versus == [duplicate]
(20 answers)
Closed 8 years ago.
This is what I am doing
FIRST ACTIVITY
public void onClick(View v) {
Intent intent = new Intent(TeamsActivity.this,PakistaniPlayers.class).putExtra("StringName","hello");
startActivity(intent);
}
SECOND ACTIVITY
if(getIntent().getStringExtra("StringName")=="hello")
{
TextView t=(TextView) findViewById(R.id.textView1);
t.setText(getIntent().getStringExtra("StringName"));
}
Now the code inside the if statement doesn't run but if I run the statements inside the if statement separately I get hello displayed.
As #anil already said, you can't compare strings like this in java.
There are three main functions of the String class that can compare two strings with each other:
equals
equalsIgnoreCase
matches
String test1 = "Hello";
String test2 = "hello";
test1.equalsIgnoreCase(test2); //isn't case-sensitive, so true.
test1.equals(test2); //is case-sensitive, so false.
test1.matches("[hH]ello"); //takes regexp, and will, in this case, be true.
test2.matches("[hH]ello"); //takes regexp, and will, in this case, be true.
General hint: If you don't care about whitespace-exact matches, eg: " Hello" should also match "Hello" I would recommend you to always test1.trim() your strings, especially if it's parsed content.
As #Panther said, for String type you should use equals when you want compare content. So the code if(getIntent().getStringExtra("StringName").equals("hello")) works and the code if(getIntent().getStringExtra("StringName")=="hello") does not.
Also, you can call getExtra many times, it always returns the same value.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I´m having trouble with the while statement. I´ve narrowed it down to my use of the "!=", because if I try it with "==", then the program works, except opposite to how I want it to. What do I use to make it so that if the user types in "v", then it won´t display the user´s input, since there´s no such thing as "!==" :)
Scanner scannerUi = new Scanner(System.in);
String userInput = scannerUi.nextLine();
while (userInput != "v") {
System.out.println(userInput);
userInput = scannerUi.nextLine();
}
use
while (!userInput.equals("v")) {
System.out.println(userInput);
userInput = scannerUi.nextLine();
}
I think that u need to compare string not on reference equality as u do it but on value equality.
So, if u want to compare your current string with some other (such as "v") just use:
userInput.equals("some_string")
Using "==" u will compare strings on reference equality, and using "equals()" u will compare strings on value equality
you should always use equals() method for compairing the strings, because equals method examine the content and == method examine the references.
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.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am still new to Java. I am trying to create a program where users must answer a multiple choice quiz. The users will input their answer and these inputs will be formed into an array. Then I plan on using a for loop to compare the user's answers array to the array of correct answers to tell the user if they are right or wrong.
However it seems that i am not properly comparing the 2 arrays in my if statement. Every time I run the program, it goes straight to the else statements.
My hunch is that the scanner class does not actually store the value?
Can anyone help?
Part of code below:
//Above this section is just a collection of "System.out.println" statements that state questions and answers the user choose from.
int x;
String answers [] = {"a", "a", "b"};
//answers array has the correct answer
Scanner in = new Scanner(System.in);
String answerEntered [] = new String [5];
//user input will be in this arra
for(x=0 ; x<3 ; x++)
{
System.out.print((1+x)+". ");
answerEntered[x] = in.nextLine();
}
for( x=0; x<3; x++)
{
**if(answerEntered[x] == answers[x])
{
System.out.println("For Question "+(x+1)+", you are Correct!");
}**
//This if section does not seem to work. Every time i run the code it automatically goes to the else statement.
else
{
System.out.println("The correct answer for Question "+(x+1)+" is: "+answers[x]);
}
}
In Java, String aren't primitive values, you have to use String.equals() to compare strings
so, change this:
if(answerEntered[x] == answers[x])
to
if(answerEntered[x].equals(answers[x]))
I would also suggest that you check for nullability and ignore case, so:
String answer = answerEntered[x];
boolean isAnswerCorrect =
answer != null &&
//remove trailling spaces and ignore case (a==A)
answer.trim().equalsIgnoreCase(answers[x]);
if(isAnswerCorrect){
For String or any object-equality test in Java, you should almost always be using equals. The == operator only compares references when used with objects (but will work the way you expect it to with primitives like int, boolean, etc); that is, it checks to see if the operands both point/refer to the same object instance. What you're interested in doing is comparing the contents of the String instance, and equals will do that for you:
if(answerEntered[x].equals(answers[x])) {
...
}
For String comparison, you need to use equals instead of ==, which for non-primitive data types, such as String, compares their references, not values.
String a = "foo";
String b = "bar";
if (a.equals(b))
{
//doSomething
}
The problem is in the comparison :
String a = "foo";
String b = "bar";
if (a.equals(b))
//doSomething
AS it Has been answered before.
Extra information, in the for loop of the if / else you are looping only the first 3 positions, not the 5 that exists in the answerEntered array.
Cheers
Use .equals to compare strings. equals compares the values, where == compares the reference
.
In Java, == comparison compares reference identity, means the two things you compare must be the same object. Two objects with the same values are treated as different.
You statement:
if(answerEntered[x] == answers[x])
The answerEntered contains string that is different with any string in answer even if they have the same value.
Java uses Object's .equals method to compare by value, i.e. Two objects are equal as long as they have the same value.
Changing:
if(answerEntered[x] == answers[x])
to
if(answerEntered[x].equals(answers[x]))
should solve the problem.
Also, as answerEntered contains user inputed value, you'd better pre-process it before using it. For example, user might put answer "a " with spaces at the end. You might want to get rid of those spaces as well.
Otherwise "a " will be treated as an incorrect answer.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
String.equals versus == [duplicate]
(20 answers)
Closed 9 years ago.
I'm having a slight problem that i can't understand, i'm building a Web Server that handles calls in the java E.G go to use /SendCommand.html then Java will handle the request, i have a login system built using post, but for some reason my login check is not working,
private boolean checkLogin(String user, String pass){
for(int i = 0; i < users.users.length; i++ ){
String test = SHA1.toSHA1(pass);
if(users.users[i][0] == user && users.users[i][1] == test ){
return true;
}
}
return false;
}
I'm Breaking at the if statment to provide the information below When i debug this i get,
Name | Type | Value
users Users #163
users String[] #165(length=1)
[0] String[] #167
[0] String "Admin"
[1] String "d033e22ae348aeb5660fc2140aec35850c4da997"
user String "Admin"
pass String "admin"
test String "d033e22ae348aeb5660fc2140aec35850c4da997"
As you can see users.users[0][0] == user and users.users[0][1] == test why is it returning false from the method?
Don't use == to compare strings. Use s1.equals(s2) instead. The former compares references, which is almost always not what you want. The latter, on the other hand, compares character sequences.
Use .equals() to compare strings, not ==.
if(users.users[i][0].equals(user) && users.users[i][1].equals(test))
Always compare String with .equals()