在下面的代码中,我只是想计算一个项目在文件中出现的次数。但是,当我打印出键和它们的值时,我得到的计数比实际值多一个。当我初始化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) {
}
}
}