Java Lesson 16: Handling of null

From Erlands Wiki

Jump to: navigation, search

The main class 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 helper class looks as follows:

public class ArgumentHelper {
    public static Argument getArgument(int argumentNumber, String[] args) {
        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 Argument looks as follows:

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

The IntArgument looks as follows:

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 looks as follows:

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

Your work is to update the main method in the main class so it can be executed as:

java MyClass 5

And give the output like:

You specified: 5

But it should also be possible to execute the program as:

java MyClass 5 Hello

And then it should give the output like:

You specified: 5
You specified: Hello

You are not allowed to have a if-statement in the main method that checks if args.length<2, the if-statement is only allowed to look at the return value from ArgumentHelper. Look in the ArgumentHelper code to see what it returns if the arguments could not be retrieved.

Personal tools