Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a console menu for user to make a selection

Tags:

java

eclipse

menu

Doing a program in Eclipse with Java. What I want to do is when I execute the program I want present the user with a choice. I have all the calculations etc. done, I'm just unsure as to how to make this menu to offer the user choices. Example of what I'm looking for:

To enter an original number: Press 1
To encrypt a number: Press 2
To decrypt a number: Press 3
To quit: Press 4
Enter choice:


public static void main(String[] args) {
    Data data = new Data(); 
    data.menu(); }
}
like image 302
PrgmRNoob Avatar asked Dec 12 '22 08:12

PrgmRNoob


1 Answers

For simplicity's sake I would recommend using a static method that returns an integer value of the option.

    public static int menu() {

        int selection;
        Scanner input = new Scanner(System.in);

        /***************************************************/

        System.out.println("Choose from these choices");
        System.out.println("-------------------------\n");
        System.out.println("1 - Enter an original number");
        System.out.println("2 - Encrypt a number");
        System.out.println("3 - Decrypt a number");
        System.out.println("4 - Quit");

        selection = input.nextInt();
        return selection;    
    }

Once you have the method complete you would display it accordingly in your main method as follows:

    public static void main(String[] args) {

        int userChoice;

        /*********************************************************/

        userChoice = menu();

        //from here you can either use a switch statement on the userchoice 
        //or you use a while loop (while userChoice != the fourth selection)
        //using if/else statements to do your actually functions for your choices.
    }

hope this helps.

like image 169
Sh0cK v Avatar answered Feb 01 '23 23:02

Sh0cK v