Skip to content

Instantly share code, notes, and snippets.

@jakub300
Created March 23, 2016 17:45
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 jakub300/2b6c9703c9962c80fb63 to your computer and use it in GitHub Desktop.
Save jakub300/2b6c9703c9962c80fb63 to your computer and use it in GitHub Desktop.
import java.io.Console;
public class ConsoleHelper {
static Console console = System.console();
public static int askQuestion(String question, String... answers) {
System.out.println(question);
for (int i = 0; i < answers.length; i++) {
System.out.println("\t "+(i+1)+". "+answers[i]);
}
while(true) {
System.out.print("Answer: ");
String ans = console.readLine();
int ansInt = -1;
if(ans.length() > 0 && ans.matches("^[0-9]+$")) {
ansInt = Integer.parseInt(ans);
if(ansInt > 0 && ansInt <= answers.length)
return ansInt-1;
}
}
}
public static String askOpenQuestion(String question, String regexp) {
System.out.println(question);
while(true) {
System.out.print("Answer: ");
String ans = console.readLine();
if(ans.length() > 0 && ans.matches(regexp)) {
return ans;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment