trying to detect a string from a pair in a set - java

For some reason, my == operator isn't returning true when it should. I see two of the exact same strings displayed on my phone yet it's still not registering as true. Any ideas? It's a hashset of pair (string,int). getFirst returns the string in the pair.
private boolean contains(HashSet<Pair> mySet, String current) {
Iterator<Pair> temp = mySet.iterator();
String compared;
Toast.makeText(MainActivity.this, " want " +current,
Toast.LENGTH_LONG).show();
while (temp.hasNext()) {
compared = temp.next().getFirst();
Toast.makeText(MainActivity.this, compared+" "+current,
Toast.LENGTH_SHORT).show();
if (compared==current)
Toast.makeText(MainActivity.this, "found", Toast.LENGTH_SHORT).show();
}
return false;
}

Strings should not be compared with ==. In java, Strings are objects, and == will check if they are the same object reference. If you want to check if they contain the same sequence of characters, use string.equals(otherString).

Do this instead:
if(compared.equals(current))

Use the String.equals() method for comparing strings. As in if (string1.equals(string2))....

Related

i am getting wrong answer with if else block

I am comparing two strings in if else block..if it is true if block should be executed and if it is false else block should execute..but my code is always executing else block for both true & false condition..here is my code
if(deckey==keystr)
{
.
.
}
else
{
System.out.println("your unauthorised person");
System.exit(0);
}
my deckey is containing string value abc123 and for keystr i am getting the value from this which is also abc123(i am getting through arraylist)..
ArrayList<Integer> listfkey= new ArrayList<Integer>();
String keystr=" ";
for (int i = 0; i < listfkey.size(); i++) {
dech=(char)listfkey.get(i).intValue();
keystr+=dech;
}
please help me out..
Strings need to be tested for equality using the .equals method:
deckey.equals(keystr)
Not the == operator, which tests if two string instances are the same:
deckey==keystr
primatives are a different matter, but with Java objects, == will only return true if the object is being compared to itself (same memory location). For Objects, use the equals method or the Comparator interface
== is use for compare memory location, it will be right on some primitive data
String is object, so for compare it we need to use .equals() method
It come from Comparator

compare two strings with .equals() don't work

I get a string form a list and try to compare it with some strings in the values and then do some stuff
for(int i=0; i<sizeOfList; i++){
String LIST_TITLE;
LIST_TITLE = list_title.get(i); //the List list_title includes some strings
if(LIST_TITLE.equals(R.string.percentbattery)) {
//do stuff
Log.d("EQUAL!","" + LIST_TITLE);
} else if(LIST_TITLE.equals(R.string.screenrecorder) == true) {
//do stuff
Log.d("EQUAL!","" + LIST_TITLE);
} else if(LIST_TITLE.equals(R.string.eightsms) == true) {
//do stuff
Log.d("EQUAL!","" + LIST_TITLE);
} else {
// do stuff
Log.e("TITLE NOT EQUAL","" + LIST_TITLE);
}
}
If I compare my LIST_TITLE with the (R.string. ...) in my Logcat they are equal, but I get only the "TITLE NOT EQUAL" Log from the else statement.
Is there another way to compare these strings? the "==" method also don't work.
R.string.percentbattery is not a String, it's an Integer that is the ID to reference the string.
what u want is:
LIST_TITLE.equals(context.getResources.getString(R.string.percentbattery))
LIST_TITLE.equals(R.string.percentbattery)
This is incorrect, because you're trying to compare string with resource ID
You should get the string from resource first:
LIST_TITLE.equals(getResources().getString(R.string.percentbattery))
R.string.xxx is an int. You need to get the String from that res
Something like
if(LIST_TITLE.equals(getResources().getString(R.string.percentbattery)))
This is assuming you have Activity Context available. Otherwise, you would need to add a Context variable in front of getResources()
R.string.some_id is just an integer by which you can get the String from the resources.
So in order to compare Strings correctly in you case you have to do:
String precentBattery = getResources().getString(R.string.percentbattery);
if (LIST_TITLE.equals (percentBattery)) ...

Can't check string value

I am trying to check a string value in if but it always is entering the else,
what Is wrong here? Thank you
public void alertBtn(View v){
EditText text = (EditText)findViewById(R.id.editText1);
String value = text.getText().toString();
String password="asd";
if (value==password){
new AlertDialog.Builder(this)
.setTitle("Success")
.setMessage("Correct Password")
.setNeutralButton("OK", null)
.show();
}
else
new AlertDialog.Builder(this)
.setTitle("Error")
.setMessage("Wrong password")
.setNeutralButton("OK", null)
.show();
}
Using the == operator will compare the references to the strings not the string themselves.
String value = text.getText().toString();
String password="asd";
if (value.equals(password))
{
}
use equals() function
Try
if( value.equals(password) ) {
}
Use .equals or .equalsIgnoreCase() to compare strings
What is the difference between == vs equals() in Java?
if (value.equals(password)){
Also move the initialization of editText to onCreate. There is no need to initialize edittext everytime on button click
text = (EditText)findViewById(R.id.editText1); // in onCreate
and declare EditText text as class member
Look here
Use the String.equals(String other) function to compare strings, not the == operator.
The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==, but it's better not to rely on that.

Java - Compare two strings and assign value to third variable?

this is my first so I'll try to add as much info as possible so I don't get yelled at. :-)
What I am trying to do is I have 2 variables that grab text from 2 fields and take only the first character from each and assign it to those values.
This is the code that I use to get the strings. They are 2 separate calls as you would.
try { var_ContactSurname = var_ContactSurname.substring(0,1);
}
catch (Exception e){
}
I have the above again with a different variable. Now to this point it does what I want. It grabs the first letter from the fields and assigns it to the variables.
So at this point I have two variables (say with an example charater of D and R).
var_ContactSurname = R
var_ContactLicenceNumber = D
What I want to do is compare those two variables and if they match I want to return a value of TRUE, else FALSE if they don't match.
That value has to be a string as well and be assigned to a new variable called var_ContactValidate.
if (var_ContactLicenceNumber.toLowerCase().equals()var_ContactSurname.toLowerCase()){
var_ContactValidate == "TRUE";
}
else {
var_ContactValidate == "FALSE";
}
No you may notice that there might be some code missing. I am using a rules engine that does a lot of the functions for me. I can use raw Java code to do other things (like this compare)...but that's the compare that I am having a problem with.
Any ideas for that compare would be greatly appreciated.
Thanks.
i would use the String method equalsIgnoreCase()
to assign a value to a field, use a single =, not double (==).
if (var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname){
var_ContactValidate = "TRUE";
}
else {
var_ContactValidate = "FALSE";
}
check it
In addition to what already said - a simpler & more elegant version (without the if condition) could be:
var_ContactValidate = Boolean.toString(
var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname))
.toUpperCase();
Change your whole piece of code to:
if (var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname)){
var_ContactValidate == "TRUE";
}
else {
var_ContactValidate == "FALSE";
}
This combines the case insensitivity that you want, and passes through the second string as an argument of the .equalsIgnoreCase function.
Also, I am not sure what you are trying to do with the line:
var_ContactValidate == "TRUE";
If you want to assign var_ContactValidate to "TRUE" then use a single equals sign '=' as a double equals '==' compares the values instead. You may also considering using a boolean rather than a string in this case.
Here is an implementation that also checks for null values and empty Strings:
public class SurnameAndLicenseValidator {
public static void main(String[] args) {
// FALSE
validateSurnameAndLicense(null, "jb78hq");
validateSurnameAndLicense("Johnson", null);
validateSurnameAndLicense(null, null);
validateSurnameAndLicense("", "jb78hq");
validateSurnameAndLicense("Johnson", "");
validateSurnameAndLicense("", "");
validateSurnameAndLicense("johnson", "xb78hq");
// TRUE
validateSurnameAndLicense("Johnson", "jb78hq");
validateSurnameAndLicense("johnson", "jb78hq");
}
private static String validateSurnameAndLicense(String surname,
String license) {
String result;
if (surname != null
&& surname.length() > 0
&& license != null
&& license.length() > 0
&& Character.toUpperCase(surname.charAt(0)) == Character
.toUpperCase(license.charAt(0))) {
result = "TRUE";
} else {
result = "FALSE";
}
System.out.println(surname + " " + license + " " + result);
return result;
}
}
The main method is used as a unit test here. You might want to extract a real JUnit test from it, if you are into that kind of thing.

String array[0] don't pass at the if

Hello everybody I have a question:
I have a array
String[] parte
and I need of the first value of the array so I did:
String verifica = parte[0] // It can be N (for Name) L (for List) and E (for Error)
Why if I run this code and I know that "verifica" is L
if (verifica == "L") { //If code
} else { //Else code
}
it returned to me always the Else code
ThankYou sooooo much
-Matteo
Comparing Strings in Java must be done with String.equals():
if (verifica.equals("L")) { //If code
What you were trying to do was comparing two distinct objects, and not their contents.
You need to use:
if (verifica.equals("L")) { //If code
} else { //Else code
}
instead of '=='. '==' in Java checks for object identity in memory, where the functionality you're needing here is to compare String values. Took me experiencing this error to realize the difference (I come from a C# background) in Java as well.
Use the equals operator for strings:
if (verifica.equals("L"))
You want if (verifica.equals("L")) or if (verifica.compareTo("L") == 0). == is not a reliable operator for comparing strings.

Categories