[英]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);
}
}
i
inside of readfile()
, it is valid only inside of the method. readfile()
内部声明i
,则仅在方法内部有效。 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。
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.