gpt4 book ai didi

java - 按长度过滤数组元素

转载 作者:行者123 更新时间:2023-12-02 04:59:36 25 4
gpt4 key购买 nike

所以我希望能够要求用户输入数组的长度并用名称填充它。执行此操作后,程序将打印出名称及其旁边的字符串长度。

public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String names [];

// Read the number of kids
System.out.print("How many kids are there? ");
int size = sc.nextInt();

// Read the names of the kids
String [] kids = new String [size];

for (int k = 0; k < kids.length; k++)
{
System.out.print("Enter name of kid #" + k + ": ");
kids[k] = sc.next();
}
// Print all the names of the kids and the length of their names
System.out.println("Names of kids with lengths are: ");

for (int i = 0; i < kids.length; i++)
{
System.out.println(kids[i] + " " + kids[i].length());
}

在此之后,我希望用户输入一个整数,程序将在数组中搜索该长度的任何字符串,如果找到任何字符串,我希望它打印出找到的所有字符串的首字母缩写。我必须使用这个程序的方法。但我似乎无法理解这个问题。

static int countByLength(String [] names, int length)
{
int count = 0;



return count;
}


/**
* Filter an array of names and keep only those names with a given length
* @param names: an array of names
* @param length: an integer length
* @return the array of names that have the given length
*/
static String [] filterByLength(String [] names, int length)
{
String [] filtered = new String[length];

for(int k = 0; k < filtered.length; k++)
{
filtered [k] =
}

return filtered;
}

}

最佳答案

一个问题是,您不知道会有多少结果,因此数组不是最好的数据结构。我建议使用列表,例如 ArrayList。然后您可以迭代该数组,将所有匹配的字符串添加到列表中。

static List<String> filterByLength(String [] names, int length)
{
List<String> filtered = new ArrayList<String>();

for(int k = 0; k < filtered.length; k++)
{
if (names.length() == length) filtered.add(names[k]);
}

return filtered;
}

关于java - 按长度过滤数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28401372/

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