user3051934
user3051934

Reputation: 15

Need help to split in Java

I have this problem in java. When I write 3/5 + 3 it returns 18/5 and it's correct but if I write 3/5/ + 3 it returns 18/5 instead of error

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

Upvotes: 0

Views: 72

Answers (1)

Domi
Domi

Reputation: 24508

This is because the regex parser prunes empty entries: "3/5/".split("/").length will return 2.

You can avoid empty entries by making sure it does not start or end with "/":

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

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

Or throw an error if there is an empty entry:

if (s.startsWith("/") || s.endsWith("/"))
   throw new SomeError();

Upvotes: 1

Related Questions