我正在编写一个程序,它将确定文本文件的行数、字符数和平均字长。对于程序,规范说文件将作为命令行参数输入,我们应该为每个输入的文件创建一个 TestStatistic 对象。如果用户输入多个文件,我不明白如何编写代码来制作 TestStatistic 对象。
问问题
4265 次
4 回答
4
处理命令行参数的最基本方法是:
public class TestProgram
{
public static void main(final String[] args)
{
for (String s : args)
{
// do something with each arg
}
System.exit(0);
}
}
最好的方法是使用为您管理命令行参数的东西。我建议JSAP: The Java Simple Argument Parser。
于 2010-03-30T20:22:50.877 回答
1
听起来您只需要遍历命令行参数并为每个参数生成一个 TestStatistic 对象。
例如
public static void main(String[] args)
{
for (String arg : args) {
TestStatistic ts = new TestStatistic(arg); // assuming 'arg' is the name of a file
}
// etc...
于 2010-03-30T20:24:01.730 回答
1
这是其他一般答案的扩展,进一步刷新了。
public class TextFileProcessor
{
private List testStatisticObjects = new ArrayList();
private void addFile(String fileName)
{
testStatisticObjects.add(new TestStatistic(fileName));
}
public static void main(String[] args)
{
TextFileProcessor processor = new TextFileProcessor();
for (String commandLineArgument : args)
{
//consider validating commandLineArgument here
processor.addFile(commandLineArgument);
}
...
}
}
于 2010-03-30T20:48:56.187 回答
-1
您还可以使用Commons CLI 之类的工具来处理命令行。
于 2010-03-30T20:24:57.680 回答