将用户输入的字符串限制为字母和数字值

发布于 2024-09-06 12:49:43 字数 1830 浏览 3 评论 0原文

基本上,我的情况要求我检查用户从键盘输入定义的字符串在一种情况下是否仅是字母字符,在另一种情况下是否仅是数字。这是用Java编写的。

我当前的代码:

switch (studentMenu) {
                case 1: // Change all four fields
                    System.out.println("Please enter in a first name: ");

                    String firstNameIntermediate = scan.next();
                    firstName = firstNameIntermediate.substring(0,1).toUpperCase() + firstNameIntermediate.substring(1);
                    System.out.println("Please enter in a middle name");
                    middleName = scan.next();
                    System.out.println("Please enter in a last name");
                    lastName = scan.next();
                    System.out.println("Please enter in an eight digit student ID number");
                    changeID();
                    break;
                case 2: // Change first name
                    System.out.println("Please enter in a first name: ");
                    firstName = scan.next();
                    break;
                case 3: // Change middle name
                    System.out.println("Please enter in a middle name");
                    middleName = scan.next();
                    break;
                case 4: // Change last name
                    System.out.println("Please enter in a last name");
                    lastName = scan.next();
                case 5: // Change student ID:
                    changeID();
                    break;
                case 6: // Exit to main menu
                    menuExit = true;
                default:
                    System.out.println("Please enter a number from 1 to 6");
                    break;
            }
        }
    }

public void changeID() {
    studentID = scan.next();
    }

我需要确保 StudentID 仅是数字,并且每个名称段都是按字母顺序排列的。

Basically, my situation requires me to check to see if the String that is defined by user input from the keyboard is only alphabetical characters in one case and only digits in another case. This is written in Java.

my current code:

switch (studentMenu) {
                case 1: // Change all four fields
                    System.out.println("Please enter in a first name: ");

                    String firstNameIntermediate = scan.next();
                    firstName = firstNameIntermediate.substring(0,1).toUpperCase() + firstNameIntermediate.substring(1);
                    System.out.println("Please enter in a middle name");
                    middleName = scan.next();
                    System.out.println("Please enter in a last name");
                    lastName = scan.next();
                    System.out.println("Please enter in an eight digit student ID number");
                    changeID();
                    break;
                case 2: // Change first name
                    System.out.println("Please enter in a first name: ");
                    firstName = scan.next();
                    break;
                case 3: // Change middle name
                    System.out.println("Please enter in a middle name");
                    middleName = scan.next();
                    break;
                case 4: // Change last name
                    System.out.println("Please enter in a last name");
                    lastName = scan.next();
                case 5: // Change student ID:
                    changeID();
                    break;
                case 6: // Exit to main menu
                    menuExit = true;
                default:
                    System.out.println("Please enter a number from 1 to 6");
                    break;
            }
        }
    }

public void changeID() {
    studentID = scan.next();
    }

I need to make sure the StudentID is only numerical and each of the name segments are alphabetical.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

你的心境我的脸 2024-09-13 12:49:43

java.util.Scanner 已经可以使用 hasNextXXX 方法检查下一个标记是否属于给定模式/类型。

这是使用 boolean hasNext(String pattern) 使用正则表达式 [A-Za-z]+ 验证下一个标记仅包含字母:

    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter letters:");
    while (!sc.hasNext("[A-Za-z]+")) {
        System.out.println("Nope, that's not it!");
        sc.next();
    }
    String word = sc.next();
    System.out.println("Thank you! Got " + word);

这是一个示例会话:

请输入字母:
&#@#$
不,不是这样!
123
不,不是这样!
詹姆斯·邦德
谢谢!有詹姆斯

要验证下一个标记是否是可以转换为 int 的数字,请使用 hasNextInt() 然后 nextInt()

相关问题

java.util.Scanner can already check if the next token is of a given pattern/type with the hasNextXXX methods.

Here's an example of using boolean hasNext(String pattern) to validate that the next token consists of only letters, using the regular expression [A-Za-z]+:

    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter letters:");
    while (!sc.hasNext("[A-Za-z]+")) {
        System.out.println("Nope, that's not it!");
        sc.next();
    }
    String word = sc.next();
    System.out.println("Thank you! Got " + word);

Here's an example session:

Please enter letters:
&#@#$
Nope, that's not it!
123
Nope, that's not it!
james bond
Thank you! Got james

To validate that the next token is a number that you can convert to int, use hasNextInt() and then nextInt().

Related questions

泅渡 2024-09-13 12:49:43

使用正则表达式可能是最简单的方法。以下是一些示例代码:

import java.util.regex.*;

public class Test
{
    public static void main(String[] args) throws Exception
    {
        System.out.println(isNumeric("123"));
        System.out.println(isNumeric("abc"));
        System.out.println(isNumeric("abc123"));

        System.out.println(isAlpha("123"));
        System.out.println(isAlpha("abc"));
        System.out.println(isAlpha("abc123"));
    }

    private static final Pattern NUMBERS = Pattern.compile("\\d+");
    private static final Pattern LETTERS = Pattern.compile("\\p{Alpha}+");

    public static final boolean isNumeric(String text)
    {
        return NUMBERS.matcher(text).matches();
    }

    public static final boolean isAlpha(String text)
    {
        return LETTERS.matcher(text).matches();
    }
}

您可能应该编写“getAlphaInput”和“getNumericInput”方法,它们执行提示/获取/检查的适当循环,直到输入正确。或者可能只是 getInput(Pattern) 以避免为不同的模式编写类似的代码。

您还应该围绕什么算作“字母”制定要求 - 上面仅包含 az 和 AZ...如果您还需要处理重音等问题,您应该更仔细地查看 Pattern 文档并适当调整。

请注意,您也可以使用正则表达式来验证字符串长度等内容。他们非常灵活。

It's probably easiest to do this with a regular expression. Here's some sample code:

import java.util.regex.*;

public class Test
{
    public static void main(String[] args) throws Exception
    {
        System.out.println(isNumeric("123"));
        System.out.println(isNumeric("abc"));
        System.out.println(isNumeric("abc123"));

        System.out.println(isAlpha("123"));
        System.out.println(isAlpha("abc"));
        System.out.println(isAlpha("abc123"));
    }

    private static final Pattern NUMBERS = Pattern.compile("\\d+");
    private static final Pattern LETTERS = Pattern.compile("\\p{Alpha}+");

    public static final boolean isNumeric(String text)
    {
        return NUMBERS.matcher(text).matches();
    }

    public static final boolean isAlpha(String text)
    {
        return LETTERS.matcher(text).matches();
    }
}

You should probably write methods of "getAlphaInput" and "getNumericInput" which perform the appropriate loop of prompt/fetch/check until the input is correct. Or possibly just getInput(Pattern) to avoid writing similar code for different patterns.

You should also work out requirements around what counts as a "letter" - the above only does a-z and A-Z... if you need to cope with accents etc as well, you should look more closely at the Pattern docs and adapt appropriately.

Note that you can use a regex to validate things like the length of the string as well. They're very flexible.

糖果控 2024-09-13 12:49:43

我不确定这是最好的方法,但您可以像这样使用Character.isDigit()和Character.IsLiteral():

for( char c : myString.toCharArray() ) {
    if( !Character.isLiteral(c) ) {
        // 
    }
}

Im not sure this is the best way to do, but you could use Character.isDigit() and Character.IsLiteral() mabybe like this:

for( char c : myString.toCharArray() ) {
    if( !Character.isLiteral(c) ) {
        // 
    }
}
方圜几里 2024-09-13 12:49:43

尝试正则表达式:\d+ -- 数字,[A-Za-z]+ -- 字母

try regexp: \d+ -- numerical, [A-Za-z]+ -- alphabetical

梦里人 2024-09-13 12:49:43

我认为您无法阻止用户输入无效值,但您可以选择验证收到的数据。我是正则表达式的粉丝。真的很快,可能是这样的(所有值都初始化为空字符串):

while (!firstName.matches("^[a-zA-Z]+$")) {
    System.out.println("Please enter in a first name");
    firstName = scan.next();
}

...

while (!studentID.matches("^\\d{8}$")) {
    System.out.println("Please enter in an eight digit student ID number");
    changeID();
}

如果您走这条路,您不妨对需要验证的不同情况进行分类,并创建一些辅助方法来处理每种情况。

“正则表达式”一开始似乎让人不知所措,但学习它具有很大的价值,并且不乏相关教程。

I don't think you can prevent the users from entering invalid values, but you have the option of validating the data you receive. I'm a fan of regular expressions. Real quick, something like this maybe (all values initialized to empty Strings):

while (!firstName.matches("^[a-zA-Z]+$")) {
    System.out.println("Please enter in a first name");
    firstName = scan.next();
}

...

while (!studentID.matches("^\\d{8}$")) {
    System.out.println("Please enter in an eight digit student ID number");
    changeID();
}

If you go this route, you might as well categorize the different cases you need to validate and create a few helper methods to deal with each.

"Regex" tends to seem overwhelming in the beginning, but learning it has great value and there's no shortage of tutorials for it.

梦里寻她 2024-09-13 12:49:43

这就是代码

    public class InputLetters {
    String  InputWords;
    Scanner reader;
    boolean [] TF;
    boolean FT;     

    public InputLetters() {

        FT=false;

        while(!FT){     
            System.out.println("Enter that you want to: ");
            reader = new Scanner(System.in);
            InputWords = reader.nextLine();
            Control(InputWords);            
        }

    }


public void Control(String s){
String [] b = s.split(" ");
TF = new boolean[b.length];
    for(int i =0;i<b.length;i++){
        if(b[i].matches("^[a-zA-Z]+$")){
            TF[i]=true;
        }else
        {
            TF[i]=false;
        }               
    }
    for(int j=0;j<TF.length;j++){
        if(!TF[j]){
            FT=false;
            System.out.println("Enter only English Characters!");
            break;
        }else{
            FT=true;
        }

    }
}

That is the code

    public class InputLetters {
    String  InputWords;
    Scanner reader;
    boolean [] TF;
    boolean FT;     

    public InputLetters() {

        FT=false;

        while(!FT){     
            System.out.println("Enter that you want to: ");
            reader = new Scanner(System.in);
            InputWords = reader.nextLine();
            Control(InputWords);            
        }

    }


public void Control(String s){
String [] b = s.split(" ");
TF = new boolean[b.length];
    for(int i =0;i<b.length;i++){
        if(b[i].matches("^[a-zA-Z]+$")){
            TF[i]=true;
        }else
        {
            TF[i]=false;
        }               
    }
    for(int j=0;j<TF.length;j++){
        if(!TF[j]){
            FT=false;
            System.out.println("Enter only English Characters!");
            break;
        }else{
            FT=true;
        }

    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文