從輸入文件所以我計票,爲sample.txt:爲什麼我的布爾值在for循環中被跳過?
3
Homer REP
Moe IND
Barney DEM
0 1 0 2 2 0
我的代碼如下所示:
public static void main(String[] args) {
int numCans = StdIn.readInt();//Number of candidates
String[] cans = new String[numCans];//Array containing the candidates
String[] parts = new String[numCans];//Array that contains the parties.
int[] votes = new int[numCans];
int voteCount = 0;
for (int i = 0; i < numCans; i++){
cans[i] = StdIn.readString();
parts[i] = StdIn.readString();
}
while (!StdIn.isEmpty()){//for counting votes
for(int i = 0; i < votes.length; i++){
if(StdIn.readInt() == i){
votes[i]++;
StdOut.println(i);
}
}
voteCount++;
}
}
那麼最終發生的是它計算約2票。謝謝你的幫助!
預期產量是多少?你真正的問題是什麼?你有沒有試過調試你的代碼? – luk2302
您的代碼在for循環中讀取3次。所以2是你應該得到的,雖然它不是你所期望的。您的代碼應該在for循環之前調用StdIn.readInt()(並將返回的值賦給變量)。 – Shiping