Fri 24 Apr 2009
Simple Java testing with Standard Input
Posted by nola under java
This is not a ground breaking thing but something I learned a few weeks ago. I've been learning java for the past few months and its a whole different world than php, perl or ruby. I learned how to use standard in from my professor a few week ago. Say you have a program like this, where you want to get some user input.
-
import java.util.ArrayList;
-
import java.util.Scanner;
-
-
-
public class Example2 {
-
-
/**
-
* @param args
-
*/
-
ArrayList<String> studentList = new ArrayList<String>();
-
-
while(input.hasNext()) {
-
if (userInput.equalsIgnoreCase("Q")) {
-
break;
-
} else {
-
studentList.add(userInput);
-
}
-
-
}
-
-
}
-
}
-
-
}
Modifying the program slightly, you can accept standard input like:
-
import java.util.ArrayList;
-
import java.util.Scanner;
-
-
-
public class Example {
-
-
/**
-
* @param args
-
*/
-
ArrayList<String> studentList = new ArrayList<String>();
-
-
while(input.hasNext()) {
-
studentList.add(name);
-
-
}
-
-
}
-
}
-
-
}
Then you can run the program on the command line like this:
$ java Example < sample_data.txt
Name is: Bob
Name is: Charles
Name is: Henry
Name is: Emery
Name is: Chad
Not too earth shattering but may help you make a simple program easier to test!
