I am taking a course Algorithms 1 by Sedgwick (Princeton University) and trying to read an integer from standard input which represents the number of integer pairs that will be input , then a list of integer pairs from standard input.
For example:
3 //first integer represents number of pairs
12 34 //list of integer pairs
23 56
34 78
I was hoping to type:
java myProg 3 12 34 23 56 34 78
at the command prompt in windows command line and read first the 3, then in a loop and process each pair in turn.
The code given in the video is this:
package getArgs;
public class getInput {
public static void main(String[] args) {
int N = StdIn.readInt(); //read first integer
while (!Stdin.isEmpty()){ // loop through pairs
int p = StdIn.readInt();
int q = StdIn.readInt();
//process p and q //process each pair
}
}
Question:
In the code is Stdin.readInt() actual java or pseudocode?
If it is not pseudocode do I need to import a library to access StdIn?
If it is pseudocode do I use a Scanner class to replace StdIn.readInt()?
The rest of the program works , that is the union find class algorithm, this driver to test the program was not explained well and confused me a little.
Here is my revised attempt - it is ugly
public class getInput {
public static void main(String[] args) {
int i = 0; //counter;
int N = 0;
N = Integer.parseInt(args[0]); //Read first Integer
System.out.println(N ); //check it works
i = i + 1;
while ( i < N * 2 ){
int p = Integer.parseInt(args[i]); //get first of the next pair
i=i + 1;
int q = Integer.parseInt(args[i]); //get second of the next pair
System.out.println(p + " " + q ); //check
}
}
This works but is uglier than the StdIn - can anyone rewrite it using StdIn so that java recognizes StdIn?
Scannerthat wrapsSystem.inand use it to read console input.10 12 34 23 56 34 78injava myProg 10 12 34 23 56 34 78command are arguments ofjavaprogram. First argument is name of class wherejavashould search formainmethod, rest of arguments are moved onString[] argsarray. Standard input is stream which is connected tojavaprocess, which is referred viaSystem.in. By default this stream reads data from console.