This is suitable for students MAY BE. Sometimes, in programs that we have to write in academia, we just need to display a list of choices and then get a number representing the choice. Having manually to write the same code is not intelligent. Isn’t it?
I was doing the same shit right now. Then, i created a simple “factory” (Don’t get religious on this, its not a real factory) to display the choices:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class ChoiceFactory {
public static int getChoice(String choices[]){
String mainChoice = null;
Scanner in = new Scanner(System.in);
do {
if (mainChoice != null)
System.out.println("Please enter a 'decent' choice !!");
int choiceNum = 1;
for (String currentChoice:choices){
System.out.println(choiceNum+". "+currentChoice);
choiceNum ++;
}
System.out.print("Enter Choice:");
mainChoice = in.next();
} while (!mainChoice.matches("^[1-"+choices.length+"]*$"));
return Integer.valueOf(mainChoice).intValue();
}
}
|
In case you see any improvement or error, please just leave a comment, I’ll correct it right away.