I'm learning Java, and I'm completing some problems tasked to me.
I've come across a specific problem and I feel like the answer is so simple, but I just can't find it.
I need to check if given string ends with the first two characters it begins with. For example, "edited" (begins and ends with "ed") I've tried using the java endsWith and startsWith, but I keep getting an error
start = text.startsWith(text.substring(0,2));
Yeilds
Error: incompatible types required: java.lang.String found: boolean
Any help would be appreciated.
Thankyou.
You're calling startsWith
when you don't need to - you know it starts with the first two characters, by definition :)
You could have:
String start = text.substring(0, 2);
boolean valid = text.endsWith(start);
Or just collapse the two:
boolean valid = text.endsWith(text.substring(0, 2));
I'm assuming you already know the string is of length 2 or more... if not, you should check that first. (And change the variable valid
to whatever makes sense in your context.)
See more on this question at Stackoverflow