0

我的代码如下所示。

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。)那么我如何在 main 方法中引用 i 呢?

4

3 回答 3

0

你可以试试这个

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); 
    }  
}
于 2015-10-06T03:51:13.780 回答
0

您正在以一种糟糕的方式编写 java 代码:

1.首先,Java中的类名char是大写的,所以你的类需要命名为ReadFile。

  1. 您不能在 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); 
    }  
}
于 2015-09-26T17:12:10.477 回答
0
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); 
    }  
}
  • 正如 UUIIUI 在评论中所说,如果您i在 of 中声明readfile(),则它仅在方法内部有效。
  • 正如 Murli 在评论中所说,您需要在类字段中添加一个成员变量。而且它必须是静态的。
于 2015-09-26T16:56:56.237 回答