[英]Java loop and increment problem
誰能告訴我程序中的問題是什么?
String a[],b[];
int c[] = new int[b.length];
for (int j = 0; j < a.length; j++) {
for (int k = 0; k < b.length; k++) {
if (b[k].equals(a[j])) {
c[k]++;
} else {
c[k] = 0;
}
}
}
我在HashMap
存儲了數千個單詞。 現在我想在每個文件中檢查allWords
發生一個單詞的時間。
你能指出我的計划中的錯誤,或者告訴我你是如何做到的?
我認為這一行不必要地重置您的計數器:
newData[j] = 0;
嘗試刪除它:
for (int j = 0; j < oneFileWords.length; j++) {
for (int k = 0; k < allWords.length; k++) {
if (allWords[k].equals(oneFileWords[j])) {
newData[j]++;
}
}
}
如果要為每個文件中的每個單詞保留單獨的計數,則需要使用二維數組。
int newData[][] = new int[oneFileWords.length][allWords.length];
然后,您可以使用newData[j][k]
訪問它。
您可以在閱讀文件時計算單詞並將其存儲在地圖上。假設文件中的最后一個單詞是“-1”並且一行中只有一個單詞,即使單詞是“生日快樂”,我也會做某事像這樣:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
public class StackOverflow {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Map<String, Integer> countedWords = new HashMap<String, Integer>();
int numberOfWords = 0;
String word = "";
while (true) {
word = scanner.nextLine();
if (word.equalsIgnoreCase("-1")) {
break;
}
if (countedWords.containsKey(word)) {
numberOfWords = countedWords.get(word);
countedWords.put(word, ++numberOfWords);
} else {
countedWords.put(word, 1);
}
}
Iterator it = countedWords.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.