Вопрос

I'm making a log in screen. It doesn't work so I decided to display the password (saved to a file), and the inputted password to the screen for comparison.

// filePassword is the password inputted from the file as a String.
// password is the String value of the EditText on the screen.
if (password.equals(filePassword))
{
    logIn();
}

I compared Strings like this:

else 
{
    scr.setText("." + filePassword + "." + '\n' + "." + password + ".");
}

This was the String comparison:

enter image description here

I compared chars like this

else 
{
    char[] filePass = filePassword.toCharArray();
    char[] pass = password.toCharArray();
}

This was the char comparison:

enter image description here

The outputs for this char array change every time you press the button.

Obviously there is a difference in the char arrays. I have no idea why. Could it be something to do with the way I've worked with the files? Probably not, considering it didn't happen anywhere else in my project.

Is there any way to fix this comparison? Using the .toString() method on both values doesn't work.

____________________________________________________________________________________________________________________________________________

Solution

if (password.equals(filePassword))

needs to be:

if (password.equals(filePassword.trim()))

The char array comparisons will always be different. The way to compare them is this:

import java.util.Arrays; // add to top of class
scr.setText(Arrays.toString(password.toCharArray()));  
scr.append(Arrays.toString(filePassword.toCharArray()));
Это было полезно?

Решение

Could there be an extra character in any of the strings? Maybe a carriage return \r? You could use length() on both, or trim(), and compare afterwards. Or try:

System.out.println(Arrays.toString(password.toCharArray()));  
System.out.println(Arrays.toString(filePassword.toCharArray()));
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top