[英]String comparison resulting in incorrect result
I have a path URL written in a file.我有一个路径 URL 写在一个文件中。 I use the Scanner class to record that URL and output it to string variable "s".
我使用扫描仪 class 将 URL 和 output 记录到字符串变量“s”。 I then use the.equals() method to compare it and the path URL in my "gameDataFile" File object.
然后我使用 .equals() 方法将它与我的“gameDataFile”文件 object 中的路径 URL 进行比较。 The result is false, despite them being the same string as recorded in my console.
结果是错误的,尽管它们与我的控制台中记录的字符串相同。 What is happening here?
这里发生了什么?
Path URL in file:文件中的路径 URL:
src\gameData\character_data.csv
Code snippet:代码片段:
String s = in.next(); // in is a java.util.Scanner object
System.out.println(gameDataFile.getPath()); // gameDataFile is a java.io.File object
System.out.println(s);
System.out.println(s.equals(gameDataFile.getPath()));
Console output:控制台 output:
src\gameData\character_data.csv
src\gameData\character_data.csv
false
EDIT: as per request of @MTilsted, the following code snippet编辑:根据@MTilsted 的要求,以下代码片段
String s = in.next();
System.out.println("'" + gameDataFile.getPath() + "'");
System.out.println("'" + s + "'");
System.out.println(s.equals(gameDataFile.getPath()));
Results in the console output:控制台 output 中的结果:
'src\gameData\character_data.csv'
'
false
It seems to have replaced the URL with one single quotation mark好像用一个单引号代替了 URL
Try this instead:试试这个:
String s = in.next(); // in is a java.util.Scanner object
System.out.println("'" + gameDataFile.getPath() + "'"); // gameDataFile is a java.io.File object
System.out.println("'" + s + "'");
System.out.println(s.equals(gameDataFile.getPath()));
Thanks to @VGR, the problem was that the String "s" contains an addition "Carriage return" character (ascii code 13).感谢@VGR,问题在于字符串“s”包含一个附加的“回车”字符(ascii 代码 13)。
The utf8 file in windows has a BOM (byte order mark) at the start of the file by default. windows 中的 utf8 文件默认在文件开头有一个 BOM(字节顺序标记)。 It is invisible, but it really exist.
它是看不见的,但它确实存在。 I think it cause two string different even if they look the same.
我认为即使它们看起来相同,它也会导致两个字符串不同。
add a backslash before the single quote在单引号前添加反斜杠
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.