Home > Blockchain >  Variable can't be accesed outside try/catch? [duplicate]
Variable can't be accesed outside try/catch? [duplicate]

Time:10-01

This does not work.

public class Main {

    public static void main(String[] args) {

        InetAddress ip;
        try {

            ip = InetAddress.getLocalHost();
            System.out.println("Current IP address : "   ip.getHostAddress());

        }
        catch (UnknownHostException e) {

            e.printStackTrace();

        }
        String numIp = ip;
    }
}

And gives this error.

java: incompatible types: java.net.InetAddress cannot be converted to java.lang.String

Also if I remove numIp and try to print ip it says that it is not initialized, its like the variable doesn't work outside the try/catch.

CodePudding user response:

You can Cast the ip.getHostAddress().toString()

CodePudding user response:

Below is the piece of code that might help you out with the problem.

import java.io.*;  
import java.net.*;  

class Main {
  public static void main(String[] args) {
   InetAddress ip= null;
   try {
     ip = InetAddress.getLocalHost();
     System.out.println("Current IP address : "   ip.getHostAddress());
    }
   catch (UnknownHostException e) {
    e.printStackTrace();
    }
   String numIp = String.valueOf(ip).getClass().getName();
 } 
}

So basically you have to typecast the object into String in order to get the value.

  • Related