Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
corr ex
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 326
Android Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh, can you explain more on that? and thank you so much for helping
 
Campbell Ritchie
Sheriff
Pie
Posts: 49411
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic