[英]Error: Main method not found in class Binary, please define the main method as: public static void main(String[] args)
When I exercised an example code of Algorithms(by Sedgewick), I tried to run that. 当我练习算法的示例代码(由Sedgewick编写)时,我尝试运行该代码。 The execution in Eclipse failed with following error message: Error: Main method not found in class Binary, please define the main method as: public static void main(String[] args) Eclipse中的执行失败,并显示以下错误消息: 错误:在Binary类中找不到主要方法,请将该主要方法定义为:public static void main(String [] args)
The DrJava shows: DrJava显示:
java.lang.ArrayIndexOutOfBoundsException: 0
at BinarySearch.main(BinarySearch.java:61)
I think there must be something wrong with this line In in = new In(args[0]);
我认为这行肯定有问题In in = new In(args[0]);
. 。
The source code is : 源代码是:
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",and "StdIn" are three external libraries, and have been imported successful. PS:“ In”,“ StdOut”和“ StdIn”是三个外部库,已成功导入。 and the line 61 in the first error display is this line " In in = new In(args[0]); " 并且第一个错误显示中的第61行是此行“ In in = new In(args [0]);”
The part defined in.readAllInts() is following: 在.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;
}
When you access the first command line argument with 当您使用以下命令访问第一个命令行参数时
args[0]
your program will die in the way you described when there are no arguments. 没有参数时,程序将按照您描述的方式终止。
Thus, always check the presence of the arguments you expect: 因此,请始终检查期望的参数是否存在:
if (args.length == 0) {
System.err.println("Please supply command line arguments!");
}
else {
// your program logic here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.