I have written a program where I have N strings and Q queries that are also strings. The goal is to determine how many times each query appears in the N strings.
This is my code:
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();
}
}
When I run my code and enter 4 strings such as {abc,abc,abc,def} and 3 queries such as {abc,def,ghi} I expect to get 3, 1 and 0 for my output since there are 3 "abc", 1 "def" and 0 "ghi". However, the output is zero for all the queries.
I am pretty sure the problem is from the method int countStringOccurance(ArrayList arr, String str) which is supposed to give me the number of times a string is repeated in an ArrayList of Strings.
Am I missing anything here?