我寫了一個程序,其中有N個字符串和Q查詢也是字符串。目標是確定每個查詢在N個字符串中出現的次數。ArrayList中的Java計數字符串出現
這是我的代碼:
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個「abc」,1個「def」和0個「ghi」,我希望得到3,1和0的輸出。但是,所有查詢的輸出都爲零。
我敢肯定這個問題是從方法 INT countStringOccurance(ArrayList的改編,字符串str)這是應該給我的時間字符串在字符串的ArrayList重複次數。
我在這裏錯過了什麼嗎?
_don't_比較喜歡這樣的字符串 - >'如果(STR == arr.get(I))',應該是 - >'if(str.equals(arr.get(i)))' –
@Aominé謝謝!這解決了問題。 – Amir