用户输入验证,强制只包含字母的字符串 [英] User Input Validation, enforcing a string containing only letters

查看:85
本文介绍了用户输入验证,强制只包含字母的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用我的一种方法来制作用户输入验证系统……它在一定程度上可以正常工作,但是尽管有代码,但它仍然允许使用整数作为有效输入,但我不希望这样做.我如何才能更改此代码,以仅允许使用字母(字符串)作为有效输入.我对此感到困惑,我尝试使用整数对该系统进行测试,它可以完美运行,但可以使用字母,但无济于事.

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.

有见识?

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

}

推荐答案

替换

            if(scan.hasNextLine()){

使用

            if(scan.hasNext("\\p{Alpha}*")){

如果您使用hasNextLine,则扫描仪仅检查接下来是否有任何内容,特别是对于字母或其他内容.

If you use hasNextLine the scanner merely checks if it has anything up next, not particularly for letters or anything else.

在使用正则表达式时,在这种情况下,p{Alpha}*表示零个或多个字母"(但是扫描程序将查找至少一个非空格字符,因此实际上是"1个或多个字母"),扫描仪的行为与您使用hasNextInt()(正在寻找数字)进行的操作非常相似.

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

请注意,它将仅接受US-ASCII范围内的字母,因此,没有重音符号或北欧字母或类似的字母,仅是a-zA-Z.

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.

此外,请使用scan.next()而不是nextLine()读取用户名-尽管您以后可能想调用nextLine()来清理该行的其余部分.如果您使用nextLine()读取用户名,则字母后面可能有一些不是字母的内容,并且将由nextLine()读取.

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

这篇关于用户输入验证,强制只包含字母的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆