public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.example.com/example.php");
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String inputLine;
inputLine = in.readLine();
System.out.println(inputLine);
in.close();
}
I dont know too much Java and I am just trying to use the first line from a url as a string for a project.
so how can i use the variable "input line" in the same class but in another method that looks like this:
public void run(){//content}
i would appreciate any helpful answer. Thanks!
First of all, your run()
method has to be static.
Second, just pass a parameter to it: public static void run(String inputLine)
An alternative would be to make a static instance field called inputLine
, and then just use it across methods without needing a parameter on the run
method.
As a beginner, this must be mind-boggling. You may want to follow some "Java for Beginners" tutorials. These are really basic stuff.
Declare variable as Object level instead of method level:
class Test {
String inputLine;
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.example.com/example.php");
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
Test t = new Test();
t.inputLine = in.readLine();
System.out.println(inputLine);
in.close();
}
public void run() {
//inputLine will be available here
}
}
Cheers !!
You can create a private variable, asign in.readLine to it and then use that in the run() method:
private String inputLine;
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.example.com/example.php");
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
inputLine = in.readLine();
System.out.println(inputLine);
in.close();
}
public void run(){
//whatever you want to do with inputLine
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.