This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes question : retailer code must contain only 2 alphabets and 3 numbers i.e AB123 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "question : retailer code must contain only 2 alphabets and 3 numbers i.e AB123" Watch "question : retailer code must contain only 2 alphabets and 3 numbers i.e AB123" New topic
Author

question : retailer code must contain only 2 alphabets and 3 numbers i.e AB123

corr ex
Greenhorn

Joined: Sep 28, 2011
Posts: 2
so the program reads from a .txt, ie AB123.

now what i currently have is


String retailer_code = input.next();

// this is the alpha
char r_c = retailer_code.charAt(0);
char r_c1 = retailer_code.charAt(1);
String r_c6 = (""+r_c+r_c1);

// this is the number
char r_c2 = retailer_code.charAt(2);
char r_c3 = retailer_code.charAt(3);
char r_c4 = retailer_code.charAt(4);
String r_c5 = (""+r_c2 + r_c3 + r_c4);
int num = Integer.parseInt(r_c5);

now, how do i do the validation? i see my friends use try...catch.. NumberFormatException. it's just that im very new to this, so any ideas?
Ove Lindström
Ranch Hand

Joined: Mar 10, 2008
Posts: 326

You can use java.util.regex.Pattern and Matcher and use the regular expression '\w{2}\d{3}' to see if it matches.
corr ex
Greenhorn

Joined: Sep 28, 2011
Posts: 2
oh, can you explain more on that? and thank you so much for helping
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37884
    
  22
You are right to avoid NumberFormatException.
Agree about using regular expressions, but I am not convinced \w is correct. Have a look through the Java Tutorials. I think something like \[a-zA-Z]{2} instead of \w. If you go through the tutoirials, you may find some simpler way of denoting “letter only”.

You do realise those are the "real" Strings and if you want to include a \ in a String literal, you must escape it to \\. I wrote about escapes elsewhere recently. But as is usual here on "Beginning Java™" I didn't give a complete answer.
 
 
subject: question : retailer code must contain only 2 alphabets and 3 numbers i.e AB123
 
Similar Threads
float
String Tokenizer
array
How to restrict the decimal place of a floating point number?
String.split method result