1

I am reading the Algorithms (Fourth Edition) from Sedgewick. The code is like this:

package edu.princeton.cs.algs4;

import java.util.Arrays;

/**
 *  The {@code BinarySearch} class provides a static method for binary
 *  searching for an integer in a sorted array of integers.
 *  <p>
 *  The <em>indexOf</em> operations takes logarithmic time in the worst case.
 *  <p>
 *  For additional documentation, see <a href="https://algs4.cs.princeton.edu/11model">Section 1.1</a> of
 *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
 *
 *  @author Robert Sedgewick
 *  @author Kevin Wayne
 */
public class BinarySearch {

    private BinarySearch() { }
    public static int indexOf(int[] a, int key) {
        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;
    }

    @Deprecated
    public static int rank(int key, int[] a) {
        return indexOf(a, key);
    }

    public static void main(String[] args) {

        // read the integers from a file
        In in = new In(args[0]);
        int[] whitelist = in.readAllInts();

        // sort the array
        Arrays.sort(whitelist);

        // read integer key from standard input; print if not in whitelist
        while (!StdIn.isEmpty()) {
            int key = StdIn.readInt();
            if (BinarySearch.indexOf(whitelist, key) == -1)
                StdOut.println(key);
        }
    }
}

I have successfully compiled the code with:

javac -cp /Users/user/documents/algorithms/algs4-master/target/algs4-1.0.0.0.jar BinarySearch.java

But when I try to run the code, the error happens:

user$ java -cp /Users/user/documents/algorithms/algs4-master/target/algs4-1.0.0.0.jar BinarySearch Error: Could not find or load main class BinarySearch Caused by: java.lang.ClassNotFoundException: BinarySearch

Please help to tell me what has happened here. Thanks a lot!

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
hanyun2019
  • 13
  • 2

1 Answers1

1

Provide the whole package of the class where the main method is and without .java because you are running the class, not the java file:

edu.princeton.cs.algs4

javac -cp /Users/user/documents/algorithms/algs4-master/target/algs4-1.0.0.0.jar edu.princeton.cs.algs4.BinarySearch
ACV
  • 9,964
  • 5
  • 76
  • 81
  • I don't see any manifest posted – ACV Sep 05 '19 at 16:35
  • It works! Thanks to all~~ – hanyun2019 Sep 06 '19 at 00:39
  • The correct solution is: javac -cp /Users/user/documents/algorithms/algs4-master/target/algs4-1.0.0.0.jar -d . BinarySearch.java java -cp /Users/user/documents/algorithms/algs4-master/target/algs4-1.0.0.0.jar edu.princeton.cs.algs4.BinarySearch tinyW.txt < tinyT.txt – hanyun2019 Sep 06 '19 at 00:50