Java Lesson 15: Common method for argument parsing
From Erlands Wiki
The main class now looks as follows:
public class MyClass { public static void main(String[] args) { Argument argument1 = ArgumentHelper.getArgument(0,args); Argument argument2 = ArgumentHelper.getArgument(1,args); printStuff(argument1); printStuff(argument2); } public static void printStuff(Argument data) { System.out.println("You specified: "+data.getValue()); } }
The IntArgument class:
public class IntArgument extends Argument { private int intArgument; public IntArgument(int intArgument) { this.intArgument = intArgument; } public int getInt() { return intArgument; } public String getValue() { return String.valueOf(intArgument); } }
The StringArgument class:
public class StringArgument extends Argument { private String strArgument; public void setString(String arg) { this.strArgument = arg; } public String getString() { return strArgument; } public String getValue() { return String.valueOf(strArgument); } }
And the Argument class looks as follows:
public abstract class Argument { public abstract String getValue(); }
The program is as usual executed with:
java MyClass 5 Hello
Your work is to implement the ArgumentHelper class so the program compiles and gives the following output:
You specified: 5 You specified: Hello
You will need to be able to to check if an argument is a integer or a String, the following code illustrates an example of how this can be accomplished:
int argument = 0; try { argument = Integer.valueOf(parameterToCheckForStringOrInteger); // If we end up here it has successfully converted the parameter to an integer // The integer value is in the "argument" variable } catch (NumberFormatException e) { // If we end up here the parameter could not be converted to an integer // The String value is in the "parameterToCheckForStringOrInteger" variable }
