我正在嘗試寫入文件(leaders.txt),並且遇到了計算的數據在文件中顯示的方式問題。在Java中寫入文件錯誤
import java.io.*;
import java.util.*;
public class readStats {
public static int getStat(String letter, String stats) {
int count = stats.length() - stats.replace(letter, "").length();
return count;
}
public static void main(String[] args) throws FileNotFoundException {
String hitsLeader = null;
String walksLeader = null;
String hitsByPitchLeader = null;
String strikeoutsLeader = null;
String battingAverageLeader = null;
int maxHits = 0;
int maxWalks = 0;
int maxHitsByPitch = 0;
int maxStrikeouts = 0;
int maxBa = 0;
java.io.File file = new java.io.File("stats.txt");
Scanner input = new Scanner(file);
//Find out number for each category
while (input.hasNextLine()) {
String line = input.nextLine();
String[] parts = line.split(" ");
int hits = getStat("H", parts[1]);
int outs = getStat("O", parts[1]);
int walks = getStat("W", parts[1]);
int hitsByPitch = getStat("P", parts[1]);
int strikeouts = getStat("K", parts[1]);
int sacrifices = getStat("S", parts[1]);
int totalAtBats = hits + outs + strikeouts;
double ba = ((double)hits/(double)totalAtBats);
//System.out.println("Player " + parts[0]);
if (hits > maxHits) {
maxHits = hits;
hitsLeader = parts[0];
}
if (walks > maxWalks) {
maxWalks = walks;
walksLeader = parts[0];
}
if (hitsByPitch > maxHitsByPitch) {
maxHitsByPitch = hitsByPitch;
hitsByPitchLeader = parts[0];
}
if (strikeouts > maxStrikeouts) {
maxHits = hits;
strikeoutsLeader = parts[0];
}
if (ba > maxBa) {
maxHits = hits;
battingAverageLeader = parts[0];
}
//Create PrintWriter
java.io.PrintWriter output = new java.io.PrintWriter("leaders.txt");
// Print LEAGUE LEADERS to leaders.txt
output.println(parts[0]);
output.printf("BA: %.3f", ba);
output.println("H: " + hits);
output.println("BB: " + walks);
output.println("K: " + strikeouts);
output.println("HBP: " + hitsByPitch);
output.println("");
output.println("LEAGUE LEADERS");
output.println("BA: " + battingAverageLeader);
output.println("H: " + hitsLeader);
output.println("BB: " + walksLeader);
output.println("K: " + strikeoutsLeader);
output.println("HPB: " + hitsByPitchLeader);
output.close();
}
}
}
輸出在leaders.txt
Pudge
BA: 0.450H: 9
BB: 2
K: 8
HBP: 1
LEAGUE LEADERS
BA: Pudge
H: Piazza
BB: Griffey
K: Pudge
HPB: Griffey
Stats.txt
Griffey HHOHOKWOHKSPOOWSHHWWWWWWW
Piazza OOHHHKPSOHOOHWWHOSSSHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
Pudge HHHHKOOHHHSWWHHOPKKKKKKK
所需的輸出
Griffey
BA: 0.462
H: 6
BB: 9
K: 2
HBP: 1
Piazza
BA: 0.833
H: 35
BB: 2
K: 1
HBP: 1
Pudge
BA: 0.450
H: 9
BB: 2
K: 8
HBP: 1
我需要輸出顯示文件stats.txt中關聯的所有三個玩家,而不僅僅是一個。
請包括stats.txt – Alfabravo
什麼是您的輸入文件? – Blaatz0r
如何上傳輸入文件?我是新來的這個.... –