java - 创建一个控制台菜单供用户进行选择

标签 java eclipse menu

用 Java 在 Eclipse 中做一个程序。我想要做的是当我执行我想要的程序时向用户提供一个选择。我已经完成了所有的计算等,我只是不确定如何制作这个菜单来为用户提供选择。我正在寻找的示例:

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(); }
}

最佳答案

为了简单起见,我建议使用返回选项的整数值的静态方法。

    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;    
    }

完成该方法后,您将在主方法中相应地显示它,如下所示:

    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.
    }

希望这对您有所帮助。

关于java - 创建一个控制台菜单供用户进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8059259/

相关文章:

java - 用单个 pom 创建 3 场 war - Maven

menu - 如何在 Yii 中使用 emenu 扩展制作垂直菜单?

javascript - 滑动导航箭头

java - 在处理中的类中使用 controlp5 小部件

java - 如果pom不存在执行mvn install会发生什么

java - 通过 checkstyle-suppressions.xml 抑制 Google Checkstyle 警告

html - 带有顶部三 Angular 形的下拉菜单

java - 如何在 Eclipse 中构建 Java Servlet?

eclipse - 无法在 Mac 上的 Eclipse 中运行项目

Eclipse IDE 自动完成错误跳行并将光标移动到下一行的中间