import java.util.Scanner;
/**
* This program is used to allow choice confirmation in a robust way.
* All the methods in this class are static.
*
* @author Kvass
* @version 1.0
*/
public final class Confirmer
{
/**
* Prints out a menu of option choices and requires the user to select
* a valid option choice.
* @param message The prompt to display above the menu
* @param args The menu choices
* @return The option number from the menu
*/
public static int menu(String message, String... args)
{
Scanner input = new Scanner(System.in);
int choice = -1;
boolean exit = false;
do
{
try
{
System.out.println(message);
int counter = 1;
for (String s:args)
{
System.out.println(counter+") "+s);
counter++;
}
System.out.print("Enter selection number: ");
String temp = input.nextLine();
choice = Integer.parseInt(temp);
if (choice>0 && choice<counter)
exit = true;
else
System.out.println("That number was not an option.");
}
catch (Exception e)
{
System.out.println("Error: Invalid input.");
}
}
while (!exit);
return choice;
}
/**
* Displays a message and requires the user to answer yes or no.
* @param message The prompt to display above the menu
* @return true if the answer is yes, false if the answer is no.
*/
public static boolean binaryQ(String message)
{
Scanner input = new Scanner(System.in);
boolean choice = false;
boolean exit = false;
do
{
try
{
System.out.print(message);
String temp = input.nextLine();
if (temp.charAt(0) == 'y' || temp.charAt(0) == 'Y')
{
choice = true;
exit = true;
}
else if (temp.charAt(0) == 'n' || temp.charAt(0) == 'N')
{
choice = false;
exit = true;
}
else
System.out.println("It's a yes or no question.");
}
catch (Exception e)
{
System.out.println("Error: Invalid input.");
}
}
while (!exit);
return choice;
}
/**
* Default constructor: private so this object cannot be constructed
*/
private Confirmer(){}
}