字符串值看起来相同,但不是“ .equals()”。彼此 [英] String values look the same but don't ".equals()" each other

查看:158
本文介绍了字符串值看起来相同,但不是“ .equals()”。彼此的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在登录屏幕。它不起作用,所以我决定将密码(保存到文件中)和输入的密码显示在屏幕上以进行比较。

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();
}

我比较了字符串像这样:

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

这是 String 比较:

我比较了个字符

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

这是 char 比较:

每次按下按钮时,此 char数组的输出都会更改。

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

显然, char数组有所不同。我不知道为什么。可能与我处理文件的方式有关吗?考虑到它在我的项目中其他任何地方都没有发生,可能不是。

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.

有什么办法可以解决此比较问题?对两个值都使用 .toString()方法不起作用。

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

____________________________________________________________________________________________________________________________________________ >

if (password.equals(filePassword))

需要是:

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()));


推荐答案

任何字符串中都可能有多余的字符?也许回车 \r ?您可以同时使用 length() trim(),然后进行比较。或尝试:

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()));

这篇关于字符串值看起来相同,但不是“ .equals()”。彼此的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆