3

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.

skaffman
  • 381,978
  • 94
  • 789
  • 754
Sachin
  • 2,537
  • 8
  • 31
  • 38

6 Answers6

6

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

Community
  • 1
  • 1
polygenelubricants
  • 348,637
  • 121
  • 546
  • 611
4

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.

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
  • Hi @jonSkeet. Suppose if i want to take 8 or less digits then what should be the solution for that. For example: I am using:- while (!in.hasNext("[0-1]+")) { System.out.println("Nope, that's not it!"); in.next(); } With this the user can enter the combination of 0-1 as many a times. But I want that the user can enter 8 or less numbers of 0-1. Like the user can enter 10101010, 101010, 01010 etc.. But not 101010101 or 010101010101 etc. Thanks in advance. – Vibhav Chaddha Dec 01 '16 at 09:22
  • @VibhavChaddha: You use `[01]{1,8}`. See the `Pattern` documentation for more details. – Jon Skeet Dec 01 '16 at 09:35
0

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) ) {
        // 
    }
}
InsertNickHere
  • 3,507
  • 3
  • 24
  • 23
0

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.

Lauri Lehtinen
  • 9,869
  • 2
  • 27
  • 28
0

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

Alex Zharnasek
  • 509
  • 5
  • 9
0

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

    }
}