这就是我想要输出的内容:
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循环在前面添加数字。
请告诉我您的见解。
谢谢!
答案 0 :(得分:0)
尝试类似:
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;
}