gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:00:41 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com