当我练习算法的示例代码(由 Sedgewick 编写)时,我尝试运行它。在 Eclipse 中执行失败并显示以下错误消息: 错误:在二进制类中找不到主方法,请将主方法定义为: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”是三个外部库,已经导入成功。并且第一个错误显示中的第 61 行是这一行“ In in = new In(args[0]); ”
在.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;
}