如果你的文件bowling.txt
看起來像這樣
Fred Blue 20 Hilda Blue 24 Pat Blue 51
然後你就可以使用Java代碼類似下面的閱讀和輸出。
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Scanner fin = new Scanner(new FileReader("bowling.txt"));
String Team, Member;
int teamw, teamb, Score;
String[] blue_members = new String[3];
String[] white_members = new String[3];
int[] blue_scores = new int[3];
int[] white_scores = new int[3];
int b = 0;
int w = 0;
System.out.println(
"This program reads the lines from the file bowling.txt to determine\n"
+ "the winner of a bowling match. The winning team, members and scores\n"
+ "are displayed on the monitor.\n");
while (fin.hasNext()) {
Member = fin.next();
Team = fin.next();
Score = fin.nextInt();
if (Team.equals("Blue")) {
blue_members[b] = Member;
blue_scores[b] = Score;
b++;
} else {
white_members[w] = Member;
white_scores[w] = Score;
w++;
}
}
if (sumArray(blue_scores) > sumArray(white_scores)) {
printArray("Blue", blue_members, blue_scores);
} else {
printArray("White", white_members, blue_scores);
}
fin.close();
}
public static int sumArray(int[] Score) {
int sum = 0;
for (int i = 0; i < Score.length; i++)
sum += Score[i];
return sum;
}
public static void printArray(String Team, String[] Member, int[] Score) {
System.out.println("Winning team:" + Team+"\n");
System.out.println("Player Score" +"\n");
for (int i = 0; i < Member.length; i++) {
System.out.printf(Member[i] + ":" + Score[i] +"\n");
}
}
}
輸出
This program reads the lines from the file bowling.txt to determine
the winner of a bowling match. The winning team, members and scores
are displayed on the monitor.
Winning team:Blue
Player Score
Fred:20
Hilda:24
Pat:51
Process finished with exit code 0
不要惡意破壞你的帖子。 –