gpt4 book ai didi

Java计算ArrayList中字符串出现的次数

转载 作者:行者123 更新时间:2023-12-01 07:19:40 25 4
gpt4 key购买 nike

我编写了一个程序,其中有 N 个字符串和 Q 个也是字符串的查询。目标是确定每个查询在 N 个字符串中出现的次数。

这是我的代码:

import java.util.Scanner;
import java.util.ArrayList;

public class SparseArrays{


// count the number of occurances of a string in an array
int countStringOccurance(ArrayList<String> arr, String str){
int count = 0;
for (int i=0; i<arr.size(); i++) {
if (str==arr.get(i)) {
count += 1;
}
}
return count;
}


void start(){
// scanner object
Scanner input = new Scanner(System.in);

// ask for user to input num strings
System.out.println("How many string would you like to enter?");
// store the number of strings
int numStrings = input.nextInt();
// to get rid of extra space
input.nextLine();

// ask user to enter strings
System.out.println("Enter the "+numStrings+" strings.");
ArrayList<String> stringInputArray = new ArrayList<String>();
for (int i=0; i<numStrings; i++) {
stringInputArray.add(input.nextLine());
} // all strings are in the stringInputArray

// ask user to input num queries
System.out.println("Enter number of queries.");
int numQueries = input.nextInt();
// to get rid of extra space
input.nextLine();

// ask user to enter string queries
System.out.println("Enter the "+numQueries+" queries.");
ArrayList<String> stringQueriesArray = new ArrayList<String>();
for (int i=0; i<numQueries; i++) {
stringQueriesArray.add(input.nextLine());
} // all string queries are in the stringQueriesArray

for (int i=0; i<stringQueriesArray.size(); i++) {
int result =
countStringOccurance(stringInputArray,stringQueriesArray.get(i));
System.out.println(result);
}
}

void printArr(ArrayList<String> arr){
for (int i=0; i<arr.size(); i++) {
System.out.println(arr.get(i));
}
System.out.println(" ");
}

public static void main(String[] args) {
SparseArrays obj = new SparseArrays();
obj.start();
}
}

当我运行代码并输入 4 个字符串(例如 {abc,abc,abc,def})和 3 个查询(例如 {abc,def,ghi})时,我期望输出为 3、1 和 0,因为有3 个“abc”、1 个“def”和 0“ghi”。但是,所有查询的输出均为零。

我很确定问题出在方法上int countStringOccurance(ArrayList arr, String str) 它应该给出字符串在字符串 ArrayList 中重复的次数。

我在这里遗漏了什么吗?

最佳答案

使用String.equals()来比较字符串,而不是==。而不是:

if (str1==str2)   //  WRONG!!!

if (str1.equals(str2))  // Correct

关于Java计算ArrayList中字符串出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43860021/

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