I need some help with this problem - Java's startsWith() method doesn't seem to be working.
Does someone know why is this happening?
The method:
public boolean check(File f) {
boolean ans = (f.getName().startsWith(this.pre));
System.out.println(f.getName()+" "+this.pre);
System.out.println(ans);
}
The output I get is:
file5.b file
false
Same_a.txt file
false
same_name_a.txt file
false
same_name_c.txt file
false
It looks like it's always returning false.
EDIT: You were right and I misunderstood some things... thanks and sorry for the inconvinnience.
Java's startsWith() method doesn't seem to be working.
I must break it to you that the startWith()
method does work. It is used by (I guess) millions of Java programmers / programs. The chances of a real bug in that method are vanishingly small. You should assume the problem is in your code ... unless you have watertight evidence that it isn't.
If a library method like that appears to be not working, that is either because you are not using it correctly, or because it actually >>is<< working and there is a problem with your inputs that you did not consider.
I cannot see anything wrong with the way you are using it, so the likely explanation is that the inputs are at fault.
The most likely explanation is that pre
has leading or trailing whitespace characters that you haven't noticed. Putting quotes around the strings in the println
expression is a simple way to spot this.
The other possibility is "homoglyphs". Somehow, either the name
string or the pre
string contains characters that look the same when you display them but are actually different Unicode codepoints. For example "Latin C" and "Cyrillic C" will most likely look identical on your screen ... but the codepoints are different and will compare as different.
If you have this problem, it may be simplest to spot using a debugger; i.e. set a breakpoint and single-step through the startsWith
call to see what characters are being