java try catch


  • 0
    public class Solution {
        public String validIPAddress(String IP) {
            if (isIPv4(IP)) {
                return "IPv4";
            } else if (isIPv6(IP)) {
                return "IPv6";
            } else {
                return "Neither";
            }     
            
        }
        private boolean isIPv4(String IP) {
            String[] array = IP.split("\\.");
            int count = 0;
            for (char c : IP.toCharArray()) {
                if (c == '.') {
                    count++;
                }
            }
            if (array.length != 4 || count != 3) {
                return false;
            }
            for (String s: array) {
                try{
                  int temp = Integer.valueOf(s);
                    if (temp < 0 || temp > 255 || (temp != 0 && s.startsWith("0")) || (temp == 0 && !s.equals("0"))) {
                        return false;
                    }  
                } catch (Exception e) {
                    return false;
                }
            }
            return true;
        }
        private boolean isIPv6(String IP) {
            String[] array = IP.split(":");
            int count = 0;
            for (char c : IP.toCharArray()) {
                if (c == ':') {
                    count++;
                }
            }
            if (array.length != 8 || count != 7) {
                return false;
            }
            for (String s: array) {
                 if (s.length() > 4) {
                    return false;
                }
                try{
                  int temp = Integer.valueOf(s, 16);
                    if (temp < 0 || temp > 65536 || (temp == 0 && !s.startsWith("0"))) {
                        return false;
                    }  
                } catch (Exception e) {
                    return false;
                }
            }
            return true;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.