Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/377.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在main方法中引用静态方法下的变量?_Java_Static Methods_Main Method - Fatal编程技术网

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

Java 如何在main方法中引用静态方法下的变量?,java,static-methods,main-method,Java,Static Methods,Main Method,我的代码如下 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); } } 如果我

我的代码如下

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); 
    }  
}
如果我不引用变量I,它工作得很好。 这意味着它可以打印出hello。 那么我如何在主方法中引用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); 
    }  
}
正如UUIUI在注释中所说,如果在readfile中声明i,则它仅在方法内部有效。 正如Murli在评论中所说,在类字段中需要一个成员变量。而且它必须是静态的。
您正在以一种糟糕的方式编写java代码:

1.首先,Java中的类名char是大写的,因此您的类需要命名为ReadFile

您不能在main方法中使用i变量,因为它只是readFile方法的一个局部变量,并且由于在main方法中使用i而存在编译错误,并且在readFile方法中存在警告,因为您没有在局部块代码中使用它。 Java对你来说是新的吗?你需要多学一点。网上有很多书或文档

您的示例已更正,编译良好,运行良好:

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); 
    }  
}
你可以试试这个

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); 
    }  
}

i是readfile的局部变量。所以u不能直接引用。你们不能在main方法中引用i,因为它是局部变量。其范围仅限于readfile函数。若你们想在main中访问它,你们需要在类中将它声明为静态变量。