Good evening from Cologne.
In a programming task I have to check if the given string consists only of letters and / or hyphens. Now I have an approach with matches. In the test of the word: "test-test-test" my code gives me false. It should be true. Do you know where the problem lies with me? Did I misunderstand at matches? I thank you in advance. Beautiful evening!
public class Zeichenketten {
public static boolean istName(String a) {
if (a.matches("[a-zA-Z]+") || a.matches("[-]+")) {
return true;
}
else {
return false;
}
}
}
Currently you're checking whether it's all letters, or all hyphens. You just need to check whether it matches letters or hyphens:
public static boolean istName(String a) {
return a.matches("[a-zA-Z-]+");
}
The -
at the end means "a hyphen" rather than "part of a range".
Note the simplification away from if/else - any time you write if (condition) return true; else return false;
you should just write return condition;
for simplicity.
See more on this question at Stackoverflow