Java中的特定字符串输入

0 java string input syntax-error

我正在制作一个程序,要求一个5位数的字符串,包含一个字母,然后是一个" - "和3个数字.(eG:A-123)我正在使用拆分分隔符" - "来拆分字母和数字,但如果输入不同于确切的格式,整个事情就会崩溃.所以我的问题是如何阻止任何不符合特定格式的输入.

到目前为止我使用的代码:

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);
   }
}
Run Code Online (Sandbox Code Playgroud)

Roh*_*ain 8

您可以使用String#matches方法检查给定输入是否为特定模式.该方法采用正则表达式.您可以像这样使用它: -

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

if如果您的输入字符串是您所描述的格式,则上述条件将返回true.即: -

[a-zA-Z]   // Start with a letter
 -         // Followed by a hyphen
\\d{3}     // And then 3 digits.
Run Code Online (Sandbox Code Playgroud)

请关注Java Naming Convention.将变量命名为以小写字母开头.


正如评论中指出的,如果使用上述方法,则甚至不需要拆分.您可以使用提取单个组件capture groups.因此,将上述模式更改为: -

([a-zA-Z])-(\\d{3})
Run Code Online (Sandbox Code Playgroud)

并且您分别在第1 第2 组中有您的字母和数字.但你必须在这里使用PatternMatcher分类.