• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 326
Android Mac OS X Firefox Browser
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
oh, can you explain more on that? and thank you so much for helping
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Tell me how it all turns out. Here is a tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic