Java loop and increment problem
Can any one tell me what is the problem in my program?
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;
}
}
}
I have thousands of words stored in a HashMap
. Now I want to check in every file that how many time one word occurred from allWords
.
Can you point out mistake in my program or give me your idea that how I can do it?
I think this line is resetting your counters unnecessarily:
newData[j] = 0;
Try removing it:
for (int j = 0; j < oneFileWords.length; j++) {
for (int k = 0; k < allWords.length; k++) {
if (allWords[k].equals(oneFileWords[j])) {
newData[j]++;
}
}
}
If you want to keep a separate count for each word in each file then you will need to use two dimensional array.
int newData[][] = new int[oneFileWords.length][allWords.length];
You can then access it using newData[j][k]
.
You could count words while reading your files and store on a Map already.. Assuming last word on file is "-1" and there's only one word in a line, even if the word is "happy birthday", I'd do something like this:
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());
}
}
}
精彩评论