0

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");
    }
}
3
  • For better help sooner, post an SSCCE. Commented Nov 30, 2013 at 11:42
  • I don't see how this could work, you're not handling the +. Commented Nov 30, 2013 at 11:45
  • What is the string you feed into the function? Just "3/5" and "3/5/", or the whole "3/5 + 3"? The latter seems improbable, because it would crash on parseInt. Commented Nov 30, 2013 at 11:46

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

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.