我必须写计数在一个文件中的行的程序,在启动程序时的文件中指定了:读取的文件名,并使用它以外主要方法
java CountText textFile.txt
在main方法我使用此代码来获得在cmd中输入的文件名:
if (args.length > 0) {
String file = args[0];
}
以外的主要方法我想再次提及这个文件名:
public void Lines() throws Exception {
FileReader fr = new FileReader (file);
无法找到符号(我没有得到,因为main方法是公共的和静态的?)。我觉得这是一个简单的解决方案,但我无法弄清楚。
编辑:由气垫船完整的鳗鱼(也特拉维斯)解决。这是一个范围问题,它通过将String传递给方法来解决。
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){...}'(尽管文件是字符串变量的错误名称 - 你会认为它应该代表一个File对象,而不是String) –
发布您的代码。我想你可能会在上下文之外声明一些变量。 – Ammar
气垫船Full Of Eels解决了这个问题。谢谢你,先生。 – astrimbu