Im trying to make a user input validation system within one of my methods... its working fine to a cetain extent, but despite the code, its still allowing for integers as valid
add a method to your code to actually scan for numbers...
something like this:
private boolean containsNumbers(String name) {
char[] chars = name.toCharArray();
for (char c : chars) {
if (c > 47 && c < 58) {
return true;
}
}
return false;
}
Replace
if(scan.hasNextLine()){
with
if(scan.hasNext("\\p{Alpha}*")){
If you use hasNextLine
the scanner merely checks if it has anything up next, not particularly for letters or anything else.
When you use a regular expression, in this case p{Alpha}*
which means "zero or more letters" (but scanner will look for at least one character that is not whitespace, so it's actually "1 or more letters"), the scanner behaves much like it does when you do the same with hasNextInt()
(which is looking for digits).
Note that it will only accept letters in the US-ASCII range, so no accents or Norse letters or anything like that, just a-zA-Z
.
Also, read the username with scan.next()
, not nextLine()
- though you may want to call nextLine()
later to clean the rest of the line. If you use nextLine()
to read the username, there might be something after the letters which is not a letter, and it will be read by nextLine()
.
I will take the code from Ubica. You can do it also like this. It is readable:
private boolean containsNumbers(String name) {
char[] chars = name.toCharArray();
for (char c : chars) {
if (Character.isDigit(c)) {
return true;
}
}
return false;
}
Try something like"
if (!userName.matches(".*\\d+.*")) {
System.out.println("Only strings no numbers");
}