gpt4 book ai didi

java - 如何在不使用映射的情况下计算字符串在数组中出现的次数?

转载 作者:行者123 更新时间:2023-11-30 08:17:18 26 4
gpt4 key购买 nike

我正在尝试计算字符串在数组中出现的次数,但我无法使用任何类型的 Map。根据我的研究,我尝试了以下方法,希望它能起作用:

int count = Collections.frequency(strings, search);

但是,当我运行程序时出现错误。该错误是空指针异常错误,我不确定如何修复该错误或发生这种情况的原因。关于我的代码有什么问题有什么想法吗?

编辑:这是我的完整代码。我找不到问题出在哪里。也许其他人可以找到它 导入java.util.*;

公开课 Lab9{

 public static void main(String[] args){
Scanner kb = new Scanner (System.in);
String name = null;
List<String> strings =null;
System.out.println("How many strings do you want to enter?:");
int size = kb.nextInt();

List<String> String = getStrings(size,name);
System.out.println(String);
System.out.println("What string would you like to search for?:");
String search = kb.next();

int numofTimes = countValues (search,strings);
System.out.print("That word appears "+numofTimes+" times in the array.");


}
public static List<String> getStrings(int size,String name) {
Scanner kb = new Scanner (System.in);
int count = 0;
List<String> strings = new ArrayList<String>();
while (count != size) {
System.out.println("Enter a string:");
name = kb.nextLine();
strings.add(name);
count = count + 1;
}

return strings;

}
public static int countValues (String search, List<String> strings){

int count = Collections.frequency(strings , search);



return count;
}



}

最佳答案

您可以通过数组进行线性搜索

    String strings[] = {"A","B",null,"C","A",null}; // the array contains nulls
String search = "A";
int count = 0;
for (int i = 0;i< strings.length ;i++ )
{
if(strings[i] != null)
{
if(strings[i].equals(search))
{
count++;
}
}
}
System.out.println(count);

关于java - 如何在不使用映射的情况下计算字符串在数组中出现的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29476954/

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