0

An IP address is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. There are two versions of the Internet protocol, and thus two versions of addresses. One of them is the IPv4 address.

IPv4 addresses are represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255 inclusive, separated by dots, e.g., 172.16.254.1.

For inputString = "172.16.254.1", the output should be isIPv4Address(inputString) = true;

For inputString = "172.316.254.1", the output should be isIPv4Address(inputString) = false

Here is my solution :

boolean isIPv4Address(String inputString) {
    String splitparts[] = inputString.split("[.]");
    if(splitparts.length != 4){
        return false;
    }
    for(String part : splitparts){
        if(part.isEmpty())
            return false;

        if(!part.matches("[0,9]{1,3}"))
            return false;

        if(!(Integer.parseInt(part)>=0 && Integer.parseInt(part)<=255))
            return false;
    }

    return true;
}

My solution is returning false in all the case and I can't find out the cause of the error. It would be great if someone reviews my code and explains to me why it's returning only false.

ra_pri
  • 155
  • 2
  • 4
  • 20
  • 2
    Use your debugger, or simply add System.out.println() statements in each branch of the code, and you'll know. – JB Nizet Jun 19 '18 at 20:36

1 Answers1

1

Your problem lies in [0,9]{1,3}. Inside the [] block, you should use a - to indicate a range. It should be [0-9]{1,3}. It was looking inside the string for 1 to 3 characters in a row that were either "0" , the literal string "," , or "9". If you want it to only accept strings that are 1 to 3 characters long, you could do:

^[0-9]{1,3}$

^ indicates the beginning, and $ the end.

FlexEast
  • 317
  • 2
  • 13
  • No problem! For reference, you actually take advantage of the way [ ] works earlier in the code--split takes a regex, and you were putting the period in the square brackets to escape it instead of using "\\." . – FlexEast Jun 19 '18 at 20:53