Java Lesson 18: Remembering position

From Erlands Wiki

Jump to: navigation, search

The main class has been changed like this:

public class MyClass {
    public static void main(String[] args) {
        ArgumentHelper helper = new ArgumentHelper(args);
        Argument argument = helper.getNextArgument();
        while(argument!=null) {
            printStuff(argument);
            argument = helper.getNextArgument();
        }
    }
 
    public static void printStuff(Argument data) {
        System.out.println("You specified: "+data.getValue());
    }
 
}

The Argument class is the same as before:

public abstract class Argument {
    public abstract String getValue();
}

The IntArgument class is the same as before:

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 is the same as before:

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);
    }
}

The helper class looks like this:

public class ArgumentHelper {
    private String[] args;
    public ArgumentHelper(String[] args) {
        this.args = args;
    }
    public Argument getArgument(int argumentNumber) {
        if(args.length>argumentNumber) {
            int argument = 0;
            try {
                argument = Integer.valueOf(args[argumentNumber]);
                // If we end up here it has successfully converted the parameter to an integer
                return new IntArgument(argument);
 
            } catch (NumberFormatException e) {
                // If we end up here the parameter could not be converted to an integer and
                StringArgument strArgument = new StringArgument();
                strArgument.setString(args[argumentNumber]);
                return strArgument;
            }
        }else {
            return null;
        }
    }
}

The program shall be possible to execute with:

java MyClass 5 Hello

And then give an output like:

You specified: 5
You specified: Hello

Your work is to change the ArgumentHelper class. You will have to replace the getArgument method with a getNextArgument method, since getNextArgument doesn’t take any argument number as parameter you will have to remember from the previous call which argument position you are on.

Personal tools