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 input, which i dont want it to be, how can i alter this code, to ONLY allow letters(strings) as valid input. im baffled at this point, i tried this system for with integers and it works flawlessly but with letters, no avail.
Insight?
public class Player {
private static String userName;
private Scanner scan = new Scanner(System.in);
private boolean validInput = false;
public void createUser(){
do {
System.out.println("Please enter you name : ");
if(scan.hasNextLine()){
userName = scan.nextLine();
validInput = true;
} else {
System.out.println("You can only use letters!");
validInput = false;
scan.next();
}
} while (!(validInput));
System.out.println(getUser());
}
static void setUser(String userName){
Player.userName = userName;
}
String getUser(){
return userName;
}
}
Try something like"
I will take the code from Ubica. You can do it also like this. It is readable:
Replace
with
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 withhasNextInt()
(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()
, notnextLine()
- though you may want to callnextLine()
later to clean the rest of the line. If you usenextLine()
to read the username, there might be something after the letters which is not a letter, and it will be read bynextLine()
.add a method to your code to actually scan for numbers...
something like this: