java - 为什么 .equals 在映射相同的字符串时返回 false?
问题描述
我试图比较一个字符串,它是读取文件的一部分(文件:读取文件的示例
1.Dog
2.Cat
3.Bird
4),对于用户给定的输入,使用 .equals。即使我复制粘贴打印的字符串,它也总是返回 false。
编码:
File TF = new File("Textfile.txt");Scanner read = new Scanner(TF);
String text="";
while(read.hasNextLine()) {
text = text.concat(read.nextLine()+"\n");
}
int x;
int y;
char a;
char b;
Random dice = new Random();
x=dice.nextInt(3)+1;
y=x+1;
a=(char)(x+48);
b=(char)(y+48);
int first = text.indexOf(a);
int second = text.indexOf(b);
String some=text.substring(first,second);
Scanner write = new Scanner(System.in);
String writein=write.nextLine();
System.out.println(writein.equals(some))
解决方案
text.substring(first,second)
返回一个包含尾随换行符的字符串,例如“1.Dog\n”,而输入的字符串不会。要修复它,您可以修剪从文件中读取的行:
String some=text.substring(first,second).trim();
推荐阅读
- laravel - 系统架构:带有微服务的 MVC 应用程序
- javascript - 我可以在 Cheetah 模板上使用 linting/fixing 工具吗?
- .net - NLog MailKit 参考版
- java - Vertx executeBatch 不返回所有行
- python - ModuleNotFoundError:没有名为“函数”python 的模块
- date - Power BI Dax 计算选定行的减法
- extjs - 在 extjs 中创建商店监听器
- networking - 如何在 Wireshark 中捕获 NBNS 数据包
- python - AttributeError:“WebElement”对象没有属性“驱动程序”
- python - 问题是用户配置文件更改表单在 Django 中始终有效