The code is from http://algs4.cs.princeton.edu/11model/BinarySearch.java.html for Algorithms textbook.
import java.
If you have already set up the environment recommended for the course, only add this lines to your java file
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
Classes StdIn
, StdOut
and In
aren't part of the standard Java libraries. They're support classes provided to go along with the Princeton course.
From the 1.1 Programming Model page linked in the source code:
Standard input and standard output. StdIn.java and StdOut.java are libraries for reading in numbers and text from standard input and printing out numbers and text to standard output. Our versions have a simpler interface than the corresponding Java ones (and provide a few tecnical improvements).
...
In.java and Out.java are object-oriented versions that support multiple input and output streams, including reading from a file or URL and writing to a file.
So if you want to use the binary search code as-is, you'll need to download those files.
You can replace then with
Output:
System.out.println(key);
Input
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String Key= null;
try {
Key = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
They are using custom libraries to print the value to console(Presumably) You can redirect the output to console.
I'm trying to use StdIn
and StdOut
by including stdlib.jar in my project and it is properly placed in the classpath, but I cannot make it work by adding:
in my own java file.
I find the solution here. I just removed package info in my java files and without any import info I can use StdIn
and StdOut
in my project since all my java files and the StdIn
, StdOut
are all in the default package.
By the way, It is a bad practice to do so in a real-world production-ready project.
StdIn and In are custom Libraries that are included within the algs4 class download. Execute the program with the command java-algs4 instead of just java and it should work.
You should use System.in
and System.out
instead of StdIn
and StdOut
.
Create an ObjectInputStream
wrapping the System input stream the following way:
ObjectInputStream ois = new ObjectInputStream(System.in);
It has a readInt
method, amd to check if it is empty, you must catch the EOFException
.