Reputation: 496
I have written a for loop, and it will only iterate once and I am not sure why. My code is:
public static void produceOutputFile() throws IOException {
PrintWriter outputFile = new PrintWriter(new FileWriter("created_output_file.txt", true));
for(int j = 0; j < hashTable.length; j++) {
System.out.println(hashTable.length);
System.out.println(j);
if(hashTable[j] != null) {
if(hashTable[j].size() > 1) {
for(int k = 0; k< hashTable[j].size(); j++) {
outputFile.write((hashTable[j].get(k).getWord()) + " " +(hashTable[j].get(k).getFrequency())+"\n");
outputFile.flush();
}
}
else {
outputFile.write((hashTable[j].get(0).getWord()) + " " +(hashTable[j].get(0).getFrequency())+ "\n");
outputFile.flush();
}
}
}
outputFile.close();
}
The output is:
16
0
I am not sure why it will not run 16 times.
Upvotes: 0
Views: 75
Reputation: 921
for(int k = 0; k< hashTable[j].size(); j++ ) {
outputFile.write((hashTable[j].get(k).getWord()) + " " +(hashTable[j].get(k).getFrequency())+"\n");
outputFile.flush();
}
In your inner for loop you increments the J. so at the first iteration j become greater than 16. so first loop doesn't iterate for second time. your code should be correct as
public static void produceOutputFile() throws IOException {
PrintWriter outputFile = new PrintWriter(new FileWriter("created_output_file.txt", true));
for(int j = 0; j < hashTable.length; j++) {
System.out.println(hashTable.length);
System.out.println(j);
if(hashTable[j] != null) {
if(hashTable[j].size() > 1) {
for(int k = 0; k< hashTable[j].size(); k++) {
outputFile.write((hashTable[j].get(k).getWord()) + " " +(hashTable[j].get(k).getFrequency())+"\n");
outputFile.flush();
}
}
else {
outputFile.write((hashTable[j].get(0).getWord()) + " " +(hashTable[j].get(0).getFrequency())+ "\n");
outputFile.flush();
}
}
}
outputFile.close();
}
here
Upvotes: 1
Reputation: 279960
In
for(int k = 0; k< hashTable[j].size(); j++) {
you're incrementing j
but using k
as an index. This loop runs forever since k
will always be smaller than hashTable[j].size()
(well, I'm assuming).
Upvotes: 4