1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Help with string.matches() in java!

  1. Nov 5, 2011 #1
    I have input from the user which is the last name, sent to be set as the last name for my object in my setLasttName method.

    public void setLastName(String lName) throws IllegalArgumentException {
    if (lName.matches("[a-zA-z'-]")) {
    this.lastName = lName; }
    else {
    throw new IllegalArgumentException("Invalid Input: name can"
    + "only consist of letters, hyphens, or apostrophes. ");
    }

    now, i am only aloud to have a-z, A-Z, hyphens, and apostrophes in the name, else i throw an exception. I have run this with putting '++' and other illegal input for lastname and it WILL NOT CATCH the exception, it continues with the program. what am i doing wrong? i have searched online forever trying to find a simple way to do this. is there an easier way that will work? Thanks so much! Last project of the quarter ^.^
    -Amanda
     
  2. jcsd
  3. Nov 5, 2011 #2

    Mark44

    Staff: Mentor

    Use [ code ] and [ /code ] tags around your code (without the spaces) to preserve indentation. I have done this for you.
    I think it might be the ' character that is causing problems. See if this makes a difference: ["a-zA-Z\'-]"
     
  4. Nov 5, 2011 #3

    Filip Larsen

    User Avatar
    Gold Member

    Some comments:
    • Your character ranges include the range A-z. You probably meant A-Z (capital z).
    • The matches method tries to match the whole string to the pattern so you would probably want to use a pattern like "[a-zA-Z'-]+" where the last + means "one or more" of the preceding pattern.
    • You say that you cannot get your code to throw IllegalArgumentException? If so, perhaps you are blind-catching the exception at some point. Check with a debugger or with debug logging that you enter the second branch of the test, or write a small unit test that calls your setter directly and checks for IllegalArgumentException.
     
  5. Nov 6, 2011 #4
    Thanks so much guys! The "+" at the end is what i needed. I'm not very familiar with the regex stuff. It seems every time i have a problem with code working its a dumb overlooking mistake. Also, thanks for the heads up on indentation! I apologize, I've never had to put code in this forum before. : )
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Help with string.matches() in java!
  1. Java Help (Replies: 6)

  2. Need java stack help (Replies: 3)

  3. JAVA ArrayList help (Replies: 5)

Loading...