java - 需要 Java 中拆分的帮助

标签 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");
    }
}

最佳答案

这是因为正则表达式解析器删除了空条目: "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();

关于java - 需要 Java 中拆分的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20299792/

相关文章:

java - 迷你搜索引擎程序主方法的用户输入

java - 使用唯一的 java.security 文件构建 Maven 项目

c# - 使用定界符拆分字符串,但在 C# 中保留结果中的定界符

java - 如何在 Eclipse 项目中包含 mysql 数据库

java - 将数据库值从 jsp 传递到 javascript

python - 在 Python 3 中将整数的字符串表示形式编码为 base64

c - 当我想在第一个字母处替换字符串时,为什么 memmove 的行为会有所不同?

java - 映射 PostgreSQL text[][] 类型和 Java 类型

java - 使用 PixelGrabber 加快图像处理速度

java - 加载属性文件 Maven 时出错