【发布时间】:2012-10-12 02:41:05
【问题描述】:
我要写一个计算文件行数的程序,启动程序时指定文件:
java CountText textFile.txt
在 main 方法中,我使用此代码获取在 cmd 中输入的文件名:
if ( args.length > 0 ) {
String file = args[0];
}
main方法之外我想再次引用这个文件名:
public void Lines() throws Exception {
FileReader fr = new FileReader ( file );
找不到符号(我没有得到,因为主要方法是公共的和静态的?)。我觉得这是一个简单的解决方案,但我想不通。
编辑:由充满鳗鱼的气垫船(也是特拉维斯)解决。这是一个范围问题,可以通过参数将字符串传递给方法来解决。
public class CountText {
public static void main ( String args[] ) throws Exception {
CountText count = new CountText();
if ( args.length > 0 ) {
String file = args[0];
count.Lines( file );
count.Words( file );
count.Characters( file );
}
}
public void Lines ( String file ) throws Exception {
FileReader fr = new FileReader ( file );
【问题讨论】:
-
为什么不简单地将字符串通过其参数传递给方法:
public void lines(String file) {...}(不过,文件对于字符串变量来说是一个坏名字——你会认为它应该代表一个文件对象,而不是一个字符串) -
发布您的代码。我认为您可能在上下文之外声明了一些变量。
-
充满鳗鱼的气垫船解决了这个问题。谢谢你,先生。
-
如果所有方法都使用相同的字符串,那么最好通过构造函数参数将它once简单地传递给类。
-
当某个答案帮助您获得您的答案时,您应该在帖子旁边标记绿色对勾。