在下面的代碼中,我只是試圖計算一個項目出現在文件中的次數。但是,當我打印出鍵和它們的值時,我得到的數字是實際存在的數字。當我初始化total
到0它修復了這個問題,但我不知道爲什麼。爲什麼我有一個錯誤?
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
public class Problem {
public static void main(String[] arg) {
HashSet QID = new HashSet();
HashMap QIDToCorrect = new HashMap();
try {
// Open the file that is the first command line parameter
FileInputStream fstream = new FileInputStream(
"C:/Users/lol/Downloads/data.csv");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//Read File Line By Line
String strLine;
br.readLine(); //skip header line
int total = 0;
int blah = 0;
while ((strLine = br.readLine()) != null) {
String[] split = strLine.split(",");
if (!QID.contains(split[0])) {
total = 1;
QID.add(split[0]);
QIDToCorrect.put(split[0], total);
} else {
total += 1;
QIDToCorrect.put(split[0], total);
}
//System.out.println();
}
} catch (Exception e) {
}
}
}
你是什麼意思?你在哪裏打印值? – Smit
你每次找到一個你從未見過的單詞時,似乎都會將總數重置爲1。那是故意的嗎? –
是的,我的鍵是項目,值是計數。如果我沒有看到一個項目,那麼我總共初始化爲1,因爲我第一次看到它。 – cooldudezen