【问题标题】:How to make a console-based menu out of an array?如何从数组中制作基于控制台的菜单?
【发布时间】:2016-10-25 23:53:34
【问题描述】:

我正在尝试为将来的工作创建一个库,作为作业的一部分,我已经完成了大部分工作,但是我不知道如何从用户输入的数组中创建基于控制台的菜单。澄清一下,我不是在要求答案,因为我才刚刚开始,但我想要的是一个很好的起点,比如命令或我可以使用的东西。我会 pos`/** * 使用选项中的字符串作为菜单生成基于控制台的菜单 * 项目。当 withQuit 为真时,为“退出”选项保留数字 0。 * * @param 选项 * - 代表菜单选项的字符串 * @param withQuit * - 当为真时为“退出”添加选项 0 * @return 用户选择的整数 */

    public static int promptForMenuSelection(String[] options, boolean withQuit) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    String.
}`

对不起,如果代码上面的要求难以阅读。请帮忙,这是作业中的最后两项任务之一,我已准备好完成它。

谢谢。

【问题讨论】:

    标签: java arrays menu console


    【解决方案1】:

    当您检查用户输入的内容时,您可以将其与数组的索引相匹配。例如:

    // Scanner for user input:
    Scanner scanner = new Scanner(System.in);
    
    // Gets the index (Surround with try/catch to prevent errors)
    int userRequest = Integer.ParseInt(scanner.nextLine());
    
    if(withQuit && userRequest == 0)
         return // Whatever value you want to return here on quit;
    
    if(userRequest - 1 > options.length)
         return // Whatever value you want to return when the request is out of range; 
    
    for(int i = 0; i < options.length; i++)
         if(options[i] == userRequest - 1)
              return i; // Returns the option index
    

    由于您试图返回一个整数,我假设您不会关心数组中的值。但如果你这样做,只需将 return 语句设置为:

    return options[i];
    

    并在函数头中将返回设置为 String 而不是 int。

    【讨论】:

    • 谢谢,我试试看。我不会撒谎,我并不完全理解这一切,但由于我是一个视觉学习者,我可能会在我做的时候得到它。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 2012-04-14
    • 2021-11-22
    • 1970-01-01
    相关资源
    最近更新 更多