Bryce Howard Bryce Howard - 1 year ago 65
Java Question

How do I call a Local Variable from Outside of its Method in Java

public void main(String[] args) throws Exception {

URL url = new URL("https://api.coinmarketcap.com/v1/global/");
InputStreamReader reader = new InputStreamReader(url.openStream());
MyData data = new Gson().fromJson(reader, MyData.class);

}

public static class MyData {
String total_market_cap_usd;
}


So what I need is to call this local variable "data" in a different class. So what I need is to somehow create a global variable with the same value as this local one, the problem is that the class this local variable is made from doesn't allow anything but final before it so could someone please help me out here. I'm really stumped and I haven't been able to find any resources to help me.
I'm sorry if I sound like a complete noob here because my experience in lower level coding languages is limited.

Answer Source

Based on your requirement you mentioned in comment, I tried achieving. See if it helps.

public class ChatBot {
String response;
public static void main(String[] args) throws Exception {
    ChatBot c1 = new ChatBot();
    String qry1 = c1.getResponse("total_market_cap_usd");
    System.out.println("response: "+qry1);
}
public static class MyData {
    String total_market_cap_usd;
    String total_24h_volume_usd;
}
public String getResponse(String query) {
    URL url = null;
    try {
        url = new URL("https://api.coinmarketcap.com/v1/global/");
        InputStreamReader reader = new InputStreamReader(url.openStream());
        MyData data = new Gson().fromJson(reader, MyData.class);
        switch (query) {
        case "total_market_cap_usd":
            response = data.total_24h_volume_usd;
            break;
        case "total_24h_volume_usd":
            response = data.total_24h_volume_usd;
            break;
        default:
            throw new IllegalArgumentException("Query not recognized!");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return response;
}
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download