0

I'm making a program that asks for a 5 digit string, containing a letter, then a "-" and 3 numbers.( eG: A-123) I'm using split with the delimiter "-" to split the letter and the numbers, but the whole thing falls apart if the input is different than that exact format. So my question is how to block out any input that doesn't fit with the specific format.

the code I'm using so far:

public Room(String Combo) {

   if (Combo.length() == 5){
      String delimiter = "-";
      String[] temp = Combo.split(delimiter);
      long FloorRoomNo = Integer.parseInt(temp[1]);
      long Floor = FloorRoomNo/100;
      long RoomNo = FloorRoomNo/100;

      this.Floor = (int)Floor;
      this.RoomNo = (int)RoomNo;
      Buildning = temp[0]:
   }else{
      System.err.println("Wrong input length");
      System.exit(-1);
   }
}
1
  • 1
    Check if Combo.contains(delimiter) before you make the split. (And please change it to combo with lowercase letter) Commented Jan 26, 2013 at 10:08

1 Answer 1

8

You can use String#matches method to check whether the given input is in a particular pattern. That method takes a regex. You can use it like this: -

if (combo.matches("[a-zA-Z]-\\d{3}")) {
    // valid format
}

The above if condition will return true, if your input string is of the form you described. i.e: -

[a-zA-Z]   // Start with a letter
 -         // Followed by a hyphen
\\d{3}     // And then 3 digits.

And please follow Java Naming Convention. Name your variables starting with lowercase letters.


As pointed out in comment, if you use above method, you don't even need to split. You can extract inidividual components, using capture groups. So, change the above pattern to: -

([a-zA-Z])-(\\d{3})

And you have your letter and numbers in group 1 and group 2 respectively. But you would have to use Pattern and Matcher classes here.

Sign up to request clarification or add additional context in comments.

1 Comment

When doing this there is probably no need for the remaining code anymore, because you could just define and retrieve subgroups instead of tearing the input string apart.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.