-1

My Problem: "return ipAddr" ipAddr cannot be resolved to a variable. So, is this because the method is static??

package oop.address;

    import java.net.InetAddress;

    public class address {

        public static  address createIP(String ip) {

            try {
                InetAddress ipAddr = InetAddress.getByName(ip);
            } catch (Exception e) {
                System.out.println("Fehler");
            }

                return null;
        }

         public  InetAddress get_ipAddr(){

            return ipAddr;
        }

    }

2 Answers2

1

So, is this because the method is static??

No the fact that the method is static has nothing to do with it. The problem is that ipAddr is created in createIP(), and thus only exists in the scope of the method. I believe you wanted to make it a class variable:

private static InetAddress ipAddr;

public static  address createIP(String ip) {
     try {
         ipAddr = InetAddress.getByName(ip);
     } catch (Exception e) {
         System.out.println("Fehler");
     }
     return null;
}
GBlodgett
  • 12,704
  • 4
  • 31
  • 45
0

Every {} pair will create a custom scope with it's own "lifetime", which in the case of nested blocks in a method body will be always shorter than the outer scope.

Easy fix is:

public static  address createIP(String ip) {
    InetAddress ipAddr = null;
    try {
        ipAddr = InetAddress.getByName(ip);
    } catch (Exception e) {
        System.out.println("Fehler");
    }
    return ipAddr;
}

But if you want to eliminate null, you have to either throw exception to the next stack frame (or you can just not to catch it) or specify a default value in the case of exception.

nyarian
  • 4,085
  • 1
  • 19
  • 51