E
E
Elzee2019-11-07 16:29:33
Java
Elzee, 2019-11-07 16:29:33

How to run programs from Algorithms in Java book?

I started studying the book "Algorithms in Java", I ran into the question of how to run programs through the terminal?
5dc41aae72b54624785674.png

import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

import java.util.Arrays;


public class BinarySearch {

    private BinarySearch() {
    }

    public static int indexOf(int[] a, int key) {
        int lo = 0;
        int hi = a.length - 1;
        while (lo <= hi) {
            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) {

        In in = new In(args[0]);
        int[] whitelist = in.readAllInts();

        Arrays.sort(whitelist);

        while (!StdIn.isEmpty()) {
            int key = StdIn.readInt();
            if (BinarySearch.indexOf(whitelist, key) == -1)
                StdOut.println(key);
        }
    }
}

That is, I need to create files with the txt extension and paste them into the terminal first, and then run the program itself by calling the run method? Or am I thinking wrong? Thanks in advance for your reply.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2019-11-07
@yourdreambtw

You must save the code in a file with a .Java extension.
The file name must match the class name.
Next, in the terminal, you need to go to the directory with this file and run javac filename.
Then run java classname.
For all this to work, you need the JDK. For example https://openjdk.java.net/
You can also download some IDE, for example, Intellij IDEA, everything will be built-in there, there will be syntax highlighting and convenient launch not from the console.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question