【问题标题】:Use the toString() method to print a numbered list of String Array objects使用 toString() 方法打印字符串数组对象的编号列表
【发布时间】:2016-12-03 06:37:22
【问题描述】:

这是我要输出的内容:

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循环将数字添加到前面。

请告诉我你的见解。

谢谢!

【问题讨论】:

  • "在 toString() 方法中我需要做什么..." 一些 for 循环,参见 docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
  • "我想我可以使用 length() 方法来获取数组内元素的数量 n,并使用 for 循环将数字添加到前面。"是的,这肯定会奏效。
  • 不请自来的建议:isEmpty() 可能不应该接受任何参数。相反,它应该使用成员变量来检查菜单是否为空。
  • @Code-Apprentice 我听从了你的建议,并没有使用 isEmpty() 参数。是否可以在 length() 方法中调用 isEmpty() 方法?
  • @glowstarraw 是的,这样做当然是合法的。你这样做的目的是什么?

标签: java arrays class object


【解决方案1】:

尝试类似:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    • 2014-09-13
    相关资源
    最近更新 更多