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

Ami*_*mir 0 java string arraylist

我编写了一个程序,其中我有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();
}
}
Run Code Online (Sandbox Code Playgroud)

当我运行我的代码并输入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中重复的次数.

我在这里错过了什么吗?

Kev*_*son 5

使用String.equals()比较字符串,没有==.代替:

if (str1==str2)   //  WRONG!!!
Run Code Online (Sandbox Code Playgroud)

if (str1.equals(str2))  // Correct
Run Code Online (Sandbox Code Playgroud)