为什么要使用“私有静态”?是不是在方法中看到了?
我有一个具有以下字段声明的类:
public class Game {
private static String outputFileName;
....
}
我在该类的 main
方法中设置了 outputFileName
的值。
我在类中还有一个使用 outputFileName
的 write
方法。我总是在 main
设置 outputFileName
的值后调用 write
。但write
仍然看不到outputFileName
的值。它说它等于null
。
有人可以告诉我我做错了什么吗?
添加 根据要求,我发布了更多代码:
主要内容:
String outputFileName = userName + "_" + year + "_" + month + "_" + day + "_" + hour + "_" + minute + "_" + second + "_" + millis + ".txt";
f=new File(outputFileName);
if(!f.exists()){
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("IN THE MAIN!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
System.out.println("------>" + outputFileName + "<------");
这一行向我输出文件的名称。
比在 write
中我有:
public static void write(String output) {
// Open a file for appending.
System.out.println("==========>" + outputFileName + "<============");
......
}
它输出 null。
I have a class with the following declaration of the fields:
public class Game {
private static String outputFileName;
....
}
I set the value of the outputFileName
in the main
method of the class.
I also have a write
method in the class which use the outputFileName
. I always call write
after main
sets value for outputFileName
. But write
still does not see the value of the outputFileName
. It say that it's equal to null
.
Could anybody, pleas, tell me what I am doing wrong?
ADDED
As it is requested I post more code:
In the main:
String outputFileName = userName + "_" + year + "_" + month + "_" + day + "_" + hour + "_" + minute + "_" + second + "_" + millis + ".txt";
f=new File(outputFileName);
if(!f.exists()){
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("IN THE MAIN!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
System.out.println("------>" + outputFileName + "<------");
This line outputs me the name of the file.
Than in the write
I have:
public static void write(String output) {
// Open a file for appending.
System.out.println("==========>" + outputFileName + "<============");
......
}
And it outputs null.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
似乎您有一个同名的局部变量或参数
Seems like you have a local variable or a parameter with the same name
main
代码的第一行需要是
,否则您将创建一个名为 outputFileName 的新的本地变量,并且
private static
不会被触及。on the first line of your
main
codeneeds to be
otherwise you're making a new, local, var called outputFileName, and the
private static
one isn't getting touched.