r/javahelp • • Jun 13 '20

ArrayIndexOutOfBoundsException: 0 error help. My code is exactly the same as the textbook I'm learning from (Algorithms by Sedgewick and Wayne).

Simple program to update count by 1 if three ints sum to 0, ints fed into program via a text file.

I understand (or I think I do) what the error means, basically the array is empty!

Here is the code:

The command I'm using in CMD to run program is: java ThreeSum < 1Kints.txt

public class ThreeSum
{
    public static int count(int[] a)
    {
        int n = a.length;
        int count = 0; 
        for (int i = 0; i < n; i++)
            for (int j = i+1; j < n; j++)
                for (int k = j+1; k < n; k++)
                    if (a[i] + a[j] + a[k] == 0)
                        count++; 
        return count; 
    }
    public static void main(String[] args)
    {
        In in = new In(args[0]); 
        int[] a = in.readAllInts();
        StdOut.println(count(a)); 
    }
}

Like I said, this is a direct copy from the textbook, the only thing I can think of is that the command to run this program and parse the file 1kints.txt to the In in = new In(args[0]) line is incorrect?

It's annoying because I have definitely had this program run in the past.

Sorry if this is really obvious, I cannot see, trying all day. This isn't even part of an exercise or anything.

18 Upvotes

9 comments sorted by

View all comments

2

u/mtko Jun 13 '20

Yea I think your args are wrong because of the < in your command.

You can check your args with something like this in your main method:

for (int i = 0;  i< args.length; i++) {
    System.out.printf("args[%d] = %s%n", i, args[i]);
}