My codes are like the following.
public class readfile {
public static void readfile() {
int i = 0;
System.out.println("hello");
}
public static void main(String[] args) {
readfile();
System.out.println(i);
}
}
And it works well if I do not refer to the variable i. (That means it can print out hello.) So how can I refer i in the main method?
public class readfile {
static int i;
public static void readfile() {
i = 0;
System.out.println("hello");
}
public static void main(String[] args) {
readfile();
System.out.println(i);
}
}
i
inside of readfile()
, it is valid only inside of the method. You are writing java code in a bad way :
1.First, the class name char in Java is Uppercase so your class need to be named ReadFile.
Java appear new for you? and you need to learn a litle bit more. There's a full of book or documentation on the web.
Your sample corrected, compiled well and run well :
package stackWeb;
public class ReadFile {
static int i = 0;
public static void readfile() {
System.out.println("hello");
}
public static void main(String[] args) {
readfile();
System.out.println(i);
}
}
You could try this
class readfile {
static int i =0;
public static void readfile() {
System.out.println("hello");
}
public static void main(String[] args) {
readfile();
System.out.println(i);
}
}
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.