Binyomin
Binyomin

Reputation: 367

How to write Java code which ensures that a string is exactly 5 digits long

Thanks for taking the time to look at my question.

I am working on a Java tuturial for college which I need some help with.

one of the requirements is to enter details about employees into the system, such as their name, surname , sex etc.. as well as an ID number.

This ID number may not be more then or less then 5 digits long. How would I write the code nessesary to ensure that the user does not enter more or less then five digits?

As well as this it must start with the numbers 1 or 2?

Upvotes: 1

Views: 444

Answers (3)

fireshadow52
fireshadow52

Reputation: 6516

Try something along these lines.

getID();

String getID() {
    Scanner sc = new Scanner(System.in);
    String ID = sc.next();
    sc.close();
    if (ID.length() == 5 && (ID.startsWith("1") || ID.startsWith("2"))) return ID;
    getID();
}

Upvotes: 2

COD3BOY
COD3BOY

Reputation: 12102

Guessing that you are using a TextField to get the value (ID number) from user, you can make use of the event FocusLost to achieve this.In the event handling code, You may get the value at the textfield and check it for the rules you mentioned and if necessary, you may use a JDialog to notify user.

Upvotes: 0

rsp
rsp

Reputation: 23373

You can achieve a check like this using a regular expression match on an expression that checks for digits 1 or 2, [12] at the start of the string, ^, followed by 4 digits \d{4} and the end of the string $.

Another way would be to convert to integer and check that is in the range 10000 - 29999.

Upvotes: 0

Related Questions