Skip to content

Instantly share code, notes, and snippets.

@jkeesh
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkeesh/40f02af11af8f20be116 to your computer and use it in GitHub Desktop.
Save jkeesh/40f02af11af8f20be116 to your computer and use it in GitHub Desktop.
import java.util.*;
public class ConsoleProgram{
private Scanner scanner;
public static void main(String[] args){
// Assume the class name is passed in as the first argument.
if(args.length == 0){
System.out.println("Please provide the name of the main class as an argument.");
return;
}
String mainClassName = args[0];
try{
Class mainClass = Class.forName(mainClassName);
Object obj = mainClass.newInstance();
ConsoleProgram program = (ConsoleProgram)obj;
program.run();
} catch (IllegalAccessException ex) {
System.out.println("Error in program. Make sure you extend ConsoleProgram");
} catch (InstantiationException ex) {
System.out.println("Error in program. Make sure you extend ConsoleProgram");
} catch (ClassNotFoundException ex) {
System.out.println("Error in program. Make sure you extend ConsoleProgram");
}
}
public void run(){
/* Overridden by subclass */
}
public ConsoleProgram(){
scanner = new Scanner(System.in);
}
public String readLine(String prompt){
System.out.print(prompt);
return scanner.nextLine();
}
public double readDouble(String prompt){
while(true){
String input = readLine(prompt);
try {
double n = Double.valueOf(input).doubleValue();
return n;
} catch (NumberFormatException e){
}
}
}
public int readInt(String prompt){
while(true){
String input = readLine(prompt);
try {
int n = Integer.parseInt(input);
return n;
} catch (NumberFormatException e){
}
}
}
}
public class HelloWorld extends ConsoleProgram{
public void run()
{
System.out.println("Hello world!");
int x = readInt("Type in your favorite int: ");
System.out.println(x);
double d = readDouble("Type in your favorite double: ");
System.out.println(d);
}
}
## Note you just compile as normal
## Then you run with `java` but also pass the name of the main class as the specific entry point as the first argument
$ javac HelloWorld.java
$ java HelloWorld HelloWorld
Hello world!
Type in your favorite int: 323
323
Type in your favorite double: 123.2
123.2
@emdash
Copy link

emdash commented Feb 23, 2015

Seems pretty reasonable. I tested it against my server, and I will have to add support for optionally specifying the main class when there are multiple main() methods defined.

Would suggest you try to break up the long-lines in the final version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment