Question

I have implemented a class that should compress or expand binary input from standard input using run-length encoding. I have fixed all of the errors that were flagged by my IDE, but when I actually run it I get an error.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at runlength.RunLength.main(RunLength.java:49)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)

In the code, line 49 is the following:

    switch (args[0]) {

here is the full code: 

package runlength;

import edu.princeton.cs.introcs.BinaryStdIn;
import edu.princeton.cs.introcs.BinaryStdOut;


public class RunLength {
    private static final int R   = 256;
    private static final int lgR = 8;

    public static void expand() { 
        boolean b = false; 
        while (!BinaryStdIn.isEmpty()) {
            int run = BinaryStdIn.readInt(lgR);
            for (int i = 0; i < run; i++)
                BinaryStdOut.write(b);
            b = !b;
        }
        BinaryStdOut.close();
    }

    public static void compress() { 
        char run = 0; 
        boolean old = false;
        while (!BinaryStdIn.isEmpty()) { 
            boolean b = BinaryStdIn.readBoolean();
            if (b != old) {
                BinaryStdOut.write(run, lgR);
                run = 1;
                old = !old;
            }
            else { 
                if (run == R-1) { 
                    BinaryStdOut.write(run, lgR);
                    run = 0;
                    BinaryStdOut.write(run, lgR);
                }
                run++;
            } 
        } 
        BinaryStdOut.write(run, lgR);
        BinaryStdOut.close();
    }


    public static void main(String[] args) {
        switch (args[0]) {
            case "-":
                compress();
                break;
            case "+":
                expand();
                break;
            default:
                throw new IllegalArgumentException("Illegal command line argument");
        }
    }

}

If anyone can explain to me what my problem is, I would really appreciate it.

Was it helpful?

Solution

You are getting the ArrayIndexOutOfBoundsException: 0 because you are trying to access to the first element of the array args, but this doesn't have any elements.

What can you do?

  • You should pass command-line arguments to the program when you launch it.
  • You can check if the length of args is greater than 0 before you access to its elements:

    if (args.length > 0)
        // ...
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top