Menu and Input Confirmation

kvass -1 Tallied Votes 196 Views Share

This program creates 2 methods for convenience: menu() and binaryQ(). The menu method accepts several strings as its parameters. The first of the strings is the question to be displayed at the top of the menu. The following strings are the menu choices. For instance, if you call Confirmer.menu("What is your favorite fruit?","Apple","Orange","Banana"); the program will print the following:

What is your favorite fruit?
1) Apple
2) Orange
3) Banana
Enter selection number:

The binaryQ method accepts a single string as a parameter, representing the question. Then it asks the user to answer yes or no. Capitalization of the answer will not affect the code. If the user answers with a word that begins with y or n, the computer will read it as yes or no -- this way, "yea", "yup" and "yes" are all evaluated the same way. Of course, if you answer "Yetti," the computer will still evaluate that as an affirmative answer. If the answer is yes, the method returns true; if the answer is no the method returns false.

Neither method will crash from invalid input -- instead they will simply request valid input, and will loop until valid input is provided.

BestJewSinceJC commented: legitimate post, down voted for no reason. +4
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(){}
}
kvass 70 Junior Poster

Um... someone voted this code down (-1 next to code snippet)? why? Is something wrong with it?

peter_budo 2,532 Code tags enforcer Team Colleague Featured Poster

Is this a question or code snipped?

kvass 70 Junior Poster

Snippet -- the code works. It is for ppl to use.

peter_budo 2,532 Code tags enforcer Team Colleague Featured Poster

You are missing obvious there, main method to call it program...

kvass 70 Junior Poster

...This isn't supposed to be a program that performs a set task. You are supposed to use it in your own program. The Math class does not have a main method -- it simply serves as a final class with several static methods that can be called. This class acts the same way -- it is for programmers here to use if they want to.

kvass 70 Junior Poster

Ok now I have a -2 on this snippet... can someone please tell me what people don't like about the code? Because I think it works fine, but it keeps getting votes off. There isn't supposed to be a main method -- it is just supposed to be a tool for people to use like the Math class.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Don't worry about the down voting. It is a system recently implemented in order to improve the forum.

But many people miss use it:
You will find entire threads of people complaining about how their perfectly good posts got down voted for no reason whatsoever by persons unknown.
I mean, I had a correct post that was written many months before they added that "voting system" and some days after the "Voting system" was added to this forum; I got down voted; my many months old thread!

So expect this to happen. It has happened to other posters that are much better than you and me

BestJewSinceJC 700 Posting Maven

It's respectable that you posted a code snippet, despite the many reasons one could find not to do so. So respect to you for that. And I typically just up vote or leave a reputation comment (which auto up votes) if I see down votes that appear to be for no reason.

kvass 70 Junior Poster

xD I'm not like concerned "omg they downvoted me" as much as I am concerned "omg that means something is wrong with my code that I didn't catch!" ^^ but if that's not the case idc

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.