S.Strachan S.Strachan - 1 year ago 86
Java Question

Having issues altering strings within the array

isValidElement is working fine but I am having an issue with setParts:
If the ip address from the String passed is valid, sets the instance variable parts to store it as 4 integer values.

For example, if ip = "192.000168.0.0000001", parts should become {192,168,0,1}. If the ip address passed is invalid, parts should become {0,0,0,0}

public static boolean isValidElement(String token) {
int foo = Integer.parseInt("token");
if(foo >= 0 && foo <= 255)
return true;
return false;
} catch (NumberFormatException ex){
return false;

public void setParts(String ip) {
int i;
if (isValidElement(ip) == false){
parts = new int[]{0,0,0,0};
} else
if (isValidElement(ip) == true){
for(i=0; i<parts.length; i++){
parts[i] = ip;

isValidElement is my method checking the string passed is valid or not which works fine and parts[4] being my array.

Any help is appreciated, thanks.

Answer Source

Try splitting your ip string on the . character, and then attempt to convert each String in that array to an int. If any of the conversions fail, reset the entire parts array:

try {
    String[] ipArr = ip.split(Pattern.quote("."));
    for (int i = 0; i < ipArr.length; i++) {
        parts[i] = Integer.parseInt(ipArr[i]);
} catch (NumberFormatException e) {
    parts = new int[4];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download