首页 > 解决方案 > 为什么 .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))

标签: javastringcompareequals

解决方案


text.substring(first,second)返回一个包含尾随换行符的字符串,例如“1.Dog\n”,而输入的字符串不会。要修复它,您可以修剪从文件中读取的行:

String some=text.substring(first,second).trim();

推荐阅读