简体   繁体   中英

How can I refer to a variable under a static method in the main method?

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); 
    }  
}
  • As UUIIUI says in comment, if you declare i inside of readfile() , it is valid only inside of the method.
  • As Murli says in comment, you need a member variable in the class field. And also it must be static one.

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.

  1. You cannot use the i variable in your main method, because it's just a local variable of your readFile method, and you have compilation errors, because of the use of i in the main method, and a warning in the readFile method, because you don't use it in the local block code.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM