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

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)) ...

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

Can I compare against multiple strings with the equals() method?

Is it possible to get multiple strings with .equals?
if(something.equals("String1 String2 String3")){
System.out.println(Something);
}
What I mean is:
if(choose.equals("DO IT")){
sysout blah blah blah
}
else if(choose.equals("DONT DO IT")){
...
}
No, but an alternative for many strings is to put the strings in a collection and do something like:
Set<String> strings = new HashSet<>();
strings.add("A");
strings.add("B");
strings.add("C");
if (strings.contains("D")) {
// ...
}
which is perhaps a little more concise. It's also null-safe wrt. the string you're looking to compare, which is often very useful.
Note further with Java 7 the switch statement works with strings, and that's useful if you wish to tie different actions to different strings.
If something is "String1 String2 String3" then it is equal.
If you mean contains, you can do
List<String> valid = Arrays.asList(string1, string2, string3);
if (valid.contains(something))
No you cannot. equals() takes only one object at a time.
As an alternative, you can try something like
if(something.equals("String1") || something.equals("String2") ||
something.equals("String3")) {
System.out.println(Something);
}
If you mean "can I test a string being equal to several strings in one operation", use regex:
if (something.matches("String1|String2|String3")) {
System.out.println(Something);
}
The pipe char | means "OR" in regex.
Note that in java (unlike many other languages) matches() must match the whole string - ie this is an "equals" comparison, not a "contains" comparison.
You can use a regex given the strings you match don't contain special regex characters, or are escaped.
Example:
Pattern p = Pattern.compile("^(String1|String2|String3)$");
if(p.matcher(something).find()) {
//do something
}
Or you can store the strings in a set/list and query the set:
Example:
HashSet<String> possible = new HashSet<String>();
possible.add("String1");
possible.add("String2");
possible.add("String3");
if(possible.contains(Something)) {
//do something
}
No, but you can use || to test multiple strings for equality:
if(something.equals("String1") || something.equals("String2") || something.equals("String3"))){
System.out.println(Something);
}
If you have gone through the javadocs it says
public boolean equals(Object obj); :
Indicates whether some other object is "equal to" this one.
It does not says that some other object is "equal to" these Objects.
Using equals() you can compare an Object with some other Object. It does not allow you to compare at once an Object with many other Objects. However if you want to compare an Object with many other Objects then you will need equals() for each comparasion
Well, if you want to check if there are any in such a string that don't match (aka all must match, albeit that doesn't really seem to make sense to me), then
String initString = "String1 String2 String3";
String[] splitStrings = initString.split(" ");
boolean match = true;
for(String string : splitStrings)
{
if(!string.equals(something))
{
match = false;
break;
}
}
if(match == true)
{
//did match all of them
}
else
{
//there was one that was not matched
}
If you want a "matches at least one" then it's just
String initString = "String1 String2 String3";
String[] splitStrings = initString.split(" ");
boolean match = false;
for(String string : splitStrings)
{
if(string.equals(something))
{
match = true;
break;
}
}
if(match == true)
{
//did match at least one of them
}
else
{
//didn't match any of them
}
But to be honest, Java 8 makes this simpler:
String something = "whatever";
String initString = "String1 String2 String3";
String[] splitStrings = initString.split(" ");
boolean matchAll = Arrays.stream(splitStrings).allMatch((x) -> x.equals(something));
boolean matchAny = Arrays.stream(splitStrings).anyMatch((x) -> x.equals(something));

If else statements inside jsp

I have a following problem - if else statements do not work in JSP, and to be honest I have no idea why. Basically I try to change the placeName depending on what number is stored in a string called place. After printing the values in the browser I can see the value is not changed. I am sure it is something simple but... Maybe some one had similar problem before?
<%
//requests the strings sent by previous page
String year = request.getParameter("year");
String place = request.getParameter("place");
out.print(year);
out.print(place);
String year2 = request.getParameter("year2");
String place2 = request.getParameter("place2");
//out.print(year2);
//out.print(place2);
if (place == "1")
{
placeName = "Belmullet";
}
else if (place == "2")
{
placeName = "Birr";
}
...more statements here...
else if (place == "15")
{
placeName = "Shannon airport";
};
%>
change the if condition:
if (place == "1") {
}
by
if ("1".equals(place)) {
}
and the same way for the other if conditions.
This SO question may helps you to learn the difference between == and equals().
It's because you're comparing Strings using ==. Instead, use the .equals() method.
The == operator tests to see if two object references refer to the exact same instance of an object.
The .equals() tests to see if the two objects being compared to each other are equivalent.

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.

trying to detect a string from a pair in a set

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))....

Categories