![](/img/trans.png)
[英]Error: Main method not found in class mainGUI, please define the main method as: public static void main(String[] args)
[英]Error: Main method not found in class Binary, please define the main method as: public static void main(String[] args)
當我練習算法的示例代碼(由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”是三個外部庫,已成功導入。 並且第一個錯誤顯示中的第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;
}
當您使用以下命令訪問第一個命令行參數時
args[0]
沒有參數時,程序將按照您描述的方式終止。
因此,請始終檢查期望的參數是否存在:
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.