User Input Validation, enforcing a string containing only letters

后端 未结 4 1234

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

4条回答
  •  情歌与酒
    2021-01-29 10:40

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

提交回复
热议问题