Java “choice factory”

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.

Create Inline array in Java

In Java, sometimes, we want to create to pass an array to as an argument without explicitly creating a variable to hold a reference to the array. We can do this like:

Instead of

String choices [] = {"Create a Plate","Delete a Plate","View Plates","Get Receipt"};
ChoiceFactory.getChoice(choices);

We can just do:

ChoiceFactory.getChoice(new String[] {"Create a Plate","Delete a Plate","View Plates","Get Receipt"});

Similarly, we can do the same for a list,

List acceptedTypes = new ArrayList(){{add("Kingdom");add("Class");add("Order");add("Phylum");add("Species");add("Genus");add("Family");}};

Simple :)