java - 使用 toString() 方法打印 String Array 对象的编号列表

标签 java arrays class object

这就是我想要输出的内容:

Choose an option :

(1) Water

(2) Soda pop

(3) Beer

?-> Enter an option number :

这是我的代码:

public class Menu 
{   

    private String[] optionList;

    private String openingMessage;

    private String topPrompt;

    private String closingMessage;

    private String bottomPrompt;


    public Menu(String[] options)
    {
        optionList = options;
        openingMessage = "";
        topPrompt = "Choose an option:";
        closingMessage = "";
        bottomPrompt = "Enter an option number:";
    }

    public Menu()
    {
        optionList = null;
        openingMessage = "";
        topPrompt = "";
        closingMessage = "";
        bottomPrompt = "";
    }

    public boolean isEmpty(String[] options)
    {
        if (options == null)
        {
            return true;
        }

        return false;
    }

    public int length(String[] options)
    {
        return options.length;
    }

    public String toString()
    {       
        return (topPrompt + "\n" + "?->" + " " + bottomPrompt);
    }

    public static void main(String[] args) 
    {
        String[] drink_options = {"Water", "Soda pop", "Beer"};

        Menu drinkMenu = new Menu(drink_options);

        System.out.println(drinkMenu);
        //System.out.println(drinkMenu.isEmpty(drink_options));
        //System.out.println(drinkMenu.length(drink_options));
    }

我必须在 toString() 方法中做什么,才能使括号中的数字出现在 String 数组元素的每个列表之前?我想我可以使用 length() 方法获取数组内元素的数量 n 并使用 for 循环将数字添加到前面。

请告诉我您的见解。

谢谢!

最佳答案

尝试如下:

public boolean isEmpty()
{
    return options == null || options.length == 0
}

public int length()
{
    return isEmpty() ? 0 : options.length;
}

public String toString()
{       
    String result = topPrompt + "\n";
    for (i=0; i<lenth(); i++) {
         result += "(" + (i+1)+ ") " + options[i]; 
    }
    result  += "?->" + " " + bottomPrompt);
    return result;
}

关于java - 使用 toString() 方法打印 String Array 对象的编号列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40945005/

相关文章:

python - 列为类属性

java - 即使导入也找不到类

java - 反序列化具有键变量 jackson map ObjectMapper 的 JSON 文件

java - 如何仅将类的某些属性作为 JSON 返回

php - 如何使用 PHP 将 MySQL 查询结果作为嵌套数组获取?

javascript - 从 Tensorflow.js 文本毒性检测模型返回 'predictions'

php - 如何检查php中命名空间是否存在

java - Eclipse 在调试时使用错误的构建

java - 在 jsp 页面中使用 log4j 的正确方法是什么

c++ - 二进制 I/O 到具有二维动态数组的文件