[英]How can I refer to a variable under a static method in the 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);
}
}
如果我不引用变量i,它将很好地工作。 (这意味着它可以打印出问候。)那么,如何在主方法中引用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);
}
}
readfile()
内部声明i
,则仅在方法内部有效。 您正在以错误的方式编写Java代码:
1.首先,Java中的类名称char为大写,因此您的类需要命名为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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.