User Input Validation, enforcing a string containi

2020-05-09 17:51发布

问题:

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;    
    }

}

回答1:

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().



回答2:

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;
}


回答3:

Try something like"

if (!userName.matches(".*\\d+.*")) {
    System.out.println("Only strings no numbers");
}


回答4:

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;
}