Reputation: 1
im trying to compare a String, which is a part of read file(the file: Example of read file
1.Dog
2.Cat
3.Bird
4), to a given input by a user, using .equals. It always returns false, even when i copypaste the printed String.
The code:
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))
Upvotes: 0
Views: 285
Reputation: 126
text.substring(first,second)
returns a string which contains a trailing line break, e.g. "1.Dog\n", while the string entered will not. To fix it, you could trim the line read from the file:
String some=text.substring(first,second).trim();
Upvotes: 1
Reputation: 445
The variable some
ends with \n
(or possibly \r\n
on Windows). writein
on the other has no trailing newline. When comparing strings, every character has to be equal (which is not the case).
You have multiple possible solutions to solve your problem. One of which is to call stripTrailing()
on your string (Java >= 11).
System.out.println(writein.equals(some.stripTrailing()))
Or you could manually reduce the length of the string
String some=text.substring(first, second - 1);
Upvotes: 0