i am getting wrong answer with if else block - java

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

Related

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

Comparing List elements in java

I have 2 Lists token and chords. They are populated alright. But when I try to compare the 2, they always yield a false value despite of printing identical string content when printed separately in a loop. Any ideas/workarounds?
System.out.println(token.get(i).toString().equals(chords.get(j).toString()));
Both are declared as List and initialized as ArrayList();
Both contain String objects.
while (i < tokenLength) {
System.out.println("");
int j = 0;
while (j < numberOfChords) {
System.out.println(token.get(i).toString() + " compares "
+ chords.get(j).toString());
System.out.println(token.get(i).toString()
.equals(chords.get(j).toString()));
if (token.get(i).toString() == chords.get(j).toString()
&& token.get(i).toString().length() <= maxLengthOfChord) {
foundChord.add(token.get(i));
}
j++;
}
i++;
}
gives the following output :
I also tried this
System.out.println(token.get(i).toString().equals(chords.get(j).toString()));
It always yields a false returning the same result as shown in the screenshot
You did everything right up to this point:
if (token.get(i).toString() == chords.get(j).toString()
You need to use the equals method, not ==
Cannot say why it prints false, but this is definitively wrong:
if (token.get(i).toString() == chords.get(j).toString()
Change that line to
if (token.get(i).trim().equals(chords.get(j).trim())
Equality (equals()) is not the same as identity (==).
This will compare references not values.
token.get(i).toString() == chords.get(j).toString()
You have to do:
token.get(i).toString().equals(chords.get(j).toString())
I'm not sure what exactly the problem is with your current code, but I did you the favor of simplifying it a bit...
for (String t : token) {
for (String c : chords) {
System.out.println(t + " compares " + c);
System.out.println(t.equals(c));
if (t.equals(c)) {
foundChord.add(t);
}
}
}
If I'm understanding it correctly, that you should do what your current code is trying to achieve, and it should work without errors.
toString() will by default print the hashcode of the object. This hashcode is unique for all the objects and hence it never matches with hashcode of other objects and the result is false when you compare them(even if the objects are similar). You need to override the toString() method to get expected result. May be you can return values of instance variables from toString method

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.

Comparing one ArrayList to another ArrayList using boolean method in java

I am trying to get a boolean method to return true or false on wether two arrayLists are equal to each other. The arraysLists are array and array1. The user inputs them. Right now here is the code that I thought would work:
public boolean equals(){
//if both are equal return true, else false
boolean test = false;
for(int i = 0; i < array1.size() && !test; i++){
if(array1.get(i) == (array.get(i))){
test = true;
}
}
return test;
}
except even when all the arrayLists numbers match the other arrayLists numbers, it returns false.
You don't need to overwrite the equals method, as there is one already provided for lists that does exactly what you need.
If you insist of writing it yourself there is a simple error in your code.
Because you initialize test to be false, "&& !test" lets your loop exist right at the start.
The correct version would be:
public boolean equals(){
if(array.size()!=array1.size) return false; // test for different length
for(int i = 0; i < array1.size(); i++){
if(!array1.get(i).equals(array.get(i))){
return false;
}
}
return true;
}
double equals (==) is dangerous. You are actually returning objects in your code up there, so you should definitely use equals() instead
Think that you are only iterating one array. Think what can go wrong there. Also take a look at your control statement.
If you carefully follow the flux of your code you quickly will realize why is false.
You should just 'reverse' your method. Assume the arrays are equal first. It should then check on each iteration if the element differs. If the element differs, then set a "not equal" flag. In pseudo-codee
boolean different = false;
for (each element of array 1) {
if (element != element of array 2) different = true
break;
}
You'll need to change your code to this:
public boolean equals(){
if (array1.size() != array.size()) return false;
for(int i = 0; i < array1.size(); i++){
if(!array1.get(i).equals(array.get(i))){
return false;
}
}
return true;
}
First off, you have to start with test being true and return false if you find something that isn't equal, because this clearly shows that the ArrayLists are not equal. You actually don't need the test variable at all, so I took it out. Just return false if you find something that isn't equal. If you don't find something that isn't equal, it will never return false and will just return true at the end. Second, you have to use the equals() method, because ArrayLists use the Integer class, not the int primitive so == will check if they are the same object, not if they are the same number. Lastly, to deal with comparing arrays of different sizes, you should compare their size and return false if they are not the same size, since there is no way they can be equal.

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