Reputation: 371
I am using Java String.equals() method to compare two strings. The Strings are fetched from a File, which is first read and stored each word individually by Splitting Strings using String.split() method.
But, the method equals is not yielding "true" for some String which is exactly same.
Here, I'm implementing Login Program which accepts username and password and checks from the file.dat whether the user exists or not and if exists, whether he is providing correct password or not.
Below is the Logic Snippet:
for( int j = 0; j < attrib.length-1; j += 2 )
{
if( j == 0 )
attrib[j] = attrib[j].replace("null","");
if( u.equals( attrib[j] ) )
{
if( p.equals( attrib[j+1] ) )
{
System.out.println("Sucess");
chk++;
break;
}
}
if( chk == 1 )
break;
}
Point me out where I'm wrong.
Here is the File Content from "file.dat":
ritwik/1234/ezio/5678
And, Here is the terminal output: Terminal Output
Upvotes: 0
Views: 1299
Reputation: 1699
If u is a String and attrib a String array, it will return the correct boolean.
Check if both Strings are the same. Usual mistakes:
1. String.equals is case-sensitive. So "Hello" and "hello" are not equal.
2. String.equals doesn't trim (remove spaces). So "Hello" and "Hello " are not equal.
If both of this fail, just use
System.out.println ("." + u + "==" + attrib[i] + ".");
before comparing, so you can see if they are both exactly the same, maybe there is something wrong when you initialize. (The points are to make it easier to detect spaces, but of course they are not needed).
EDIT: If this ALSO fails, try printing the char array of the string (u.toCharArray()
), in case it has some weird chars in the middle.
Upvotes: 1