Restrict string input from user to alphabetic and numerical values [duplicate]

╄→гoц情女王★ 提交于 2019-11-28 10:33:43
polygenelubricants

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

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.

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) ) {
        // 
    }
}

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

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.

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

    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!