javafor-loopindexoutofboundsexception

Array Index Out Of Bounds Error When Computing Generalized Harmonic Numbers


Beginner to java. Trying to make code that takes 2 command line arguments (n, r) and uses a for loop to compute the nth generalized harmonic number of order r.

I keep getting the error "ArrayIndexOutOfBoundsException" and I have no idea why. In the loop, I have tried i < n and i<=n and keep getting the same result.

Here is the code:

public class Main {
    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        int r = Integer.parseInt(args[1]);
        float sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += 1 / Math.pow(i, r);
        }
        System.out.println(sum);
    }
}

Edit: I am running the program from the mac command line and it's not letting me enter arguments at all. Sorry if this is missing something very obvious.


Solution

  • I believe the error has nothing to do with your harmonic numbers. Input values are the problem. If you look into the exception carefully you will see that it is thrown at the line where you extract the parameters from the command line arguments args[N]. For that is the only place where you operate with arrays in your code.

    Try this code:

    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("The program requires 2 arguments. You provided " + args.length);
            return;
        }
        int n = Integer.parseInt(args[0]);
        int r = Integer.parseInt(args[1]);
        float sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += 1 / Math.pow(i, r);
        }
        System.out.println(sum);
    }
    

    You will see that your arguments are somehow not provided. Check how do you run your program.