需要帮助来拆分Java

时间:2013-11-30 11:41:47

标签: java string

我在java中遇到这个问题。当我写3/5 + 3时它返回18/5并且它是正确的但如果我写3/5 / + 3它返回18/5而不是错误

    public static RatNum parse(String s) {
    int x = 0;
    int y = 0;
    String split[] = s.split("/");
    if (split.length == 2) {
        x = Integer.parseInt(split[0]);
        y = Integer.parseInt(split[1]);
        return new RatNum(x, y);
    } else if (split.length == 1) {
        x = Integer.parseInt(s);
        return new RatNum(x);
    } else {
        throw new NumberFormatException("Error");
    }
}

1 个答案:

答案 0 :(得分:1)

这是因为正则表达式解析器修剪了空条目: "3/5/".split("/").length将返回2.

您可以通过确保它不以“/”开头或结尾来避免空条目:

while (s.startsWith("/"))
  s = s.substring(1);

while (s.endsWith("/"))
  s = s.substring(0, s.length()-1);

如果有空条目,则抛出错误:

if (s.startsWith("/") || s.endsWith("/"))
   throw new SomeError();
相关问题