- 练习:
您在冰淇淋店试图决定您想要哪种冰淇淋和配料。有很多选择!
您决定编写一个程序来帮助您列出所有可能的选择。
编写一个方法
ArrayList getAllChoices(String[] 口味,String[] 配料) 它采用冰淇淋口味数组和配料数组作为参数,并返回一个 ArrayList,其中包含冰淇淋和配料的所有可能组合。
每个组合都应以以下形式表示
"{{flavor}} with {{topping}} on top"
其中 {{flavor}} 是提供的冰淇淋口味,例如“巧克力”,而 {{topping}} 是提供的配料,例如“洒水”。
例如方法调用:
String[] flavors = {"chocolate", "vanilla"};
String[] toppings = {"sprinkles", "fudge"};
getAllChoices(flavors, toppings);
应返回包含以下字符串的 ArrayList:
["chocolate with sprinkles on top", "chocolate with fudge on top", "vanilla with sprinkles on top", "vanilla with fudge on top"]
我有:
public ArrayList<String> getAllChoices(String[] flavors, String[] toppings)
{
String[] flavors = {"chocolate", "vanilla"};
String[] toppings = {"sprinkles", "fudge"};
for(int i = 0; i < flavors.size(); i ++)
{
for(int x = 0; x < toppings.size(); x++)
{
String flavorss = flavors[i];
String toppingss = toppings[x];
return (flavorss + " with " + toppingss + " on top");
}
}
}
不太擅长这个,也不知道为什么它不起作用。
编辑:使用此解决方案得到它。
public ArrayList<String> getAllChoices(String[] flavors, String[] toppings)
{
ArrayList<String> retList = new ArrayList<String>();
for(int i = 0; i < flavors.length; i ++)
{
for(int x = 0; x < toppings.length; x++)
{
String flavorss = flavors[i];
String toppingss = toppings[x];
// Add to list instead of returning.
retList.add(flavorss + " with " + toppingss + " on top");
}
}
return retList;
}
感谢您的帮助!
最佳答案
public ArrayList<String> getAllChoices(String[] flavors, String[] toppings)
{
ArrayList<String> retList = new ArrayList<String>();
for(int i = 0; i < flavors.length; i ++)
{
for(int x = 0; x < toppings.length; x++)
{
String flavorss = flavors[i];
String toppingss = toppings[x];
// Add to list instead of returning.
retList.add(flavorss + " with " + toppingss + " on top");
}
}
return retList;
}
您的迭代很好,但您太早返回列表了。您的执行只会返回第一个结果。
另外,这是java语法。不是 JavaScript。
关于java - 尝试显示所有可能的配料组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37711928/