2

Algorithms (by Sedgewick) のサンプル コードを実行したときに、それを実行しようとしました。Eclipse での実行が失敗し、次のエラー メッセージが表示されました: エラー: クラス Binary にメイン メソッドが見つかりません。メイン メソッドを次のように定義してください: public static void main(String[] args)

DrJava は次のことを示しています。

java.lang.ArrayIndexOutOfBoundsException: 0
    at BinarySearch.main(BinarySearch.java:61)

この行には何か問題があるに違いないと思いますIn in = new In(args[0]);

ソースコードは次のとおりです。

import java.util.Arrays;

public class BinarySearch {

    public static int rank(int key, int[] a) {
        int lo = 0;
        int hi = a.length - 1;
        while (lo <= hi) {
            // Key is in a[lo..hi] or not present.
            int mid = lo + (hi - lo) / 2;
            if      (key < a[mid]) hi = mid - 1;
            else if (key > a[mid]) lo = mid + 1;
            else return mid;
        }
        return -1;
    }


    public static void main(String[] args) {

        // read in the integers from a file
        In in = new In(args[0]); 
        int[] whitelist = in.readAllInts();

        // sort the array
        Arrays.sort(whitelist);

        // read key; print if not in whitelist
        while (!StdIn.isEmpty()) {
            int key = StdIn.readInt();
            if (rank(key, whitelist) == -1)
                StdOut.println(key);
        }
    }
}

PS: "In"、"StdOut"、および "StdIn" は 3 つの外部ライブラリであり、正常にインポートされました。最初のエラー表示の 61 行目は、この行 " In in = new In(args[0]); " です。

in.readAllInts() で定義されている部分は次のとおりです。

/**
 * Read all ints until the end of input is reached, and return them.
 */
public int[] readAllInts() {
    String[] fields = readAllStrings();
    int[] vals = new int[fields.length];
    for (int i = 0; i < fields.length; i++)
        vals[i] = Integer.parseInt(fields[i]);
    return vals;
}
4

1 に答える 1

0

で最初のコマンドライン引数にアクセスすると

args[0]

引数がない場合、プログラムは説明した方法で終了します。

したがって、期待する引数の存在を常に確認してください。

if (args.length == 0) {
    System.err.println("Please supply command line arguments!");
}
else {
   // your program logic here
}
于 2013-11-05T09:42:12.383 に答える