I'm a writing a program that will determine the number of lines, characters, and average word length for a text file. For the program, the specifications say that the file or files will be entered as a command line argument and that we should make a TestStatistic object for each file entered. I don't understand how to write the code for making the TestStatistic objects if the user enters more than one file.
+3
A:
The most basic way to process command line arguments is:
public class TestProgram
{
public static void main(final String[] args)
{
for (String s : args)
{
// do something with each arg
}
System.exit(0);
}
}
The preferable way is to use something that manages the command line arguments for you. I suggest JSAP: The Java Simple Argument Parser.
fuzzy lollipop
2010-03-30 20:22:50
You don't need to (and shouldn't) use System.exit to exist. Just let the main method return.
Steve Kuo
2010-03-31 00:26:55
explict is better than implict especially for beginners!
fuzzy lollipop
2010-03-31 02:33:57
Well it doesn't get any more explicit than assembly, so maybe they should start there? I disagree, higher abstraction is better for beginners. Obviously you agree to some degree since you're recommending the for-each construct instead of the more explicit standard for loop.
polygenelubricants
2010-03-31 02:58:27
+1
A:
It sounds like you simply need to iterate through your command line args and produce a TestStatistic object for each.
e.g.
public static void main(String[] args)
{
for (String arg : args) {
TestStatistic ts = new TestStatistic(arg); // assuming 'arg' is the name of a file
}
// etc...
Brian Agnew
2010-03-30 20:24:01
your code looks weird, the scope of ts is wrong. It would be clearer if you have a collection or something like that. That seems a bit confusing.
LB
2010-03-30 20:29:45
A:
You can also use something like Commons CLI to process command line.
lexicore
2010-03-30 20:24:57
this is a terrible suggestion, Commons CLI is a crusty crappy library that isn't even maintained and has horrible semantics.
fuzzy lollipop
2010-03-30 20:26:41
+1
A:
Here's an expansion on other general answers, flushed out a bit further.
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);
}
...
}
}
Chris Knight
2010-03-30 20:48:56