Q:

Check the number of arguments in a java program

I have a java program that has two integers as input and has to do all four mathematical operations. 
Meanwhile, I run my Java programs via terminal so the two integers are passed on as arguments. However, whenever I try to check the validity of the arguments passed I get a message saying: 
(For example, if I ran: Java Example --> without any arguments I get the following message)
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Example.main(Example.java:38)

My code is the following:
public class Example {
    public void Sum(int a, int b) {
        int sum = a + b;
        System.out.println("The sum:" + sum);
    }

    public void Sub(int a, int b) {
        int sub = a - b;
        System.out.println("The subtraction is:" + sub);
    }

    public void Mul(int a, int b) {
        int mul = a * b;
        System.out.println("The multiplication is:" + mul);
    }

    public void Div(int a, int b) {
        try {
            int div = a / b;
            System.out.println("The division is:" + div);
        } catch (ArithmeticException e) {
            System.out.println("You can't divide a number by 0");
        }
    }

    public static void main(String[] args) {
        Example c = new Example();
        int count = args.length;
        int x = Integer.parseInt(args[0]);
        int y = Integer.parseInt(args[1]);
        int z = Integer.parseInt(args[1]);

        if (count == 0 || count > 2 || count == 1) {
            System.out.println("Not valid number of arguments try again. You entered " + count + " arguments");
        } else {
            c.Sum(x, y);
            c.Sub(x, y);
            c.Mul(x, y);
            c.Div(x, y);
            System.out.println("Arguments:" + count);
            return;
        }
    }
}

What I write on the terminal is: e.g. Java Example 2 3 

A:

You need to ensure that the size of args[] is equal to 2 before trying to access args[0] and args[1]. Change main as follows:
public static void main(String[] args) {
    Example c = new Example();
    int count = args.length;
    if (count == 2) {
        int x = Integer.parseInt(args[0]);
        int y = Integer.parseInt(args[1]);

        c.Sum(x, y);
        c.Sub(x, y);
        c.Mul(x, y);
        c.Div(x, y);
        System.out.println("Arguments:" + count);
        return;
    } else {
        System.out.println("Not valid number of arguments try again. You entered " + count + " arguments");
    }
}

On a side note, you should follow Java naming conventions e.g. the names of the functions should be sum, sub, mul, div instead of Sum, Sub, Mul, Div.

