简体   繁体   English

如何在main方法的静态方法下引用变量?

[英]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. 如果我不引用变量i,它将很好地工作。 (That means it can print out hello.) So how can I refer i in the main method? (这意味着它可以打印出问候。)那么,如何在主方法中引用i?

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. 正如UUIIUI在评论中所说,如果在readfile()内部声明i ,则仅在方法内部有效。
  • As Murli says in comment, you need a member variable in the class field. 正如Murli在评论中所说,您需要在class字段中添加一个成员变量。 And also it must be static one. 而且它必须是静态的。

You are writing java code in a bad way : 您正在以错误的方式编写Java代码:

1.First, the class name char in Java is Uppercase so your class need to be named ReadFile. 1.首先,Java中的类名称char为大写,因此您的类需要命名为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. 您不能在main方法中使用i变量,因为它只是readFile方法的局部变量,并且由于在main方法中使用i以及在readFile方法中显示警告而导致编译错误,因为您没有不要在本地块代码中使用它。

Java appear new for you? Java对您来说是新的? 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); 
    }  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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