当前位置: 首页 > 知识库问答 >
问题:

错误:在类Binary中找不到Main方法,请将Main方法定义为:public static void Main(String[]args)

秦才
2023-03-14
java.lang.ArrayIndexOutOfBoundsException: 0
    at BinarySearch.main(BinarySearch.java:61)
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;
}

共有1个答案

裴劲
2023-03-14

使用访问第一个命令行参数

args[0]

当没有参数时,您的程序将以您所描述的方式死亡。

因此,始终检查所需参数的存在:

if (args.length == 0) {
    System.err.println("Please supply command line arguments!");
}
else {
   // your program logic here
}
 类似资料: