0

ランレングス エンコーディングを使用して標準入力からバイナリ入力を圧縮または展開するクラスを実装しました。IDE によってフラグが付けられたすべてのエラーを修正しましたが、実際に実行するとエラーが発生します。

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

コードの 49 行目は次のとおりです。

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

}

誰かが私の問題が何であるかを説明してくれれば、本当に感謝しています。

4

1 に答える 1

0

ArrayIndexOutOfBoundsException: 0array の最初の要素にアクセスしようとしているため、 を取得していますがargs、これには要素がありません。

あなたは何ができますか?

  • プログラムを起動するときに、コマンドライン引数をプログラムに渡す必要があります。
  • 要素にアクセスする前に、 の長さargsがより大きいかどうかを確認できます。0

    if (args.length > 0)
        // ...
    
于 2014-04-06T07:40:30.820 に答える