【发布时间】: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 是的,这样做当然是合法的。你这样做的目的是什么?