2
votes

When I exercised an example code of Algorithms(by Sedgewick), I tried to run that. 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)

The DrJava shows:

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]);.

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. and the line 61 in the first error display is this line " In in = new In(args[0]); "

The part defined in.readAllInts() is following:

/**
 * 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
class Binary is not BinarySearch - Giulio Franco
You may have renamed your Main class without changing Eclipse Run configuration. - Guillaume Poussel
What arguments do you pass to BinarySearch ? - orique

1 Answers

0
votes

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
}