问题描述
我正在尝试构建一个程序,该程序从包含20个人的.txt文件中读取信息。 每个人都有四个领域,所属的团队,击球平均值和本垒打总数。 我需要将每个人添加到他们的团队中(每个团队4个玩家),总计团队本垒打的总数,并按顺序对5个团队进行排名。 我能够将文本正确地读入一个由每个人组成的数组中,但是我无法弄清楚如何使用此数据来创建2D数组。 我将使用2D数组,将玩家分配到正确的团队中,并添加其本垒打总数。 我想对每个团队和每个个人的本垒打总数从最大到最小排序。 我已经尽力寻找答案,并在其他帖子和站点上学习,但是我对创建2D数组以及如何对它们进行排序的概念感到困惑。
更新的说明:这是单个数组的信息外观:
[Team][Name][avg][Home Runs]
然后,我只想从最大到最小对[Home Runs]列进行排序,但不知道如何仅访问数组的该部分。
2D数组应如下所示:
[Team] [Total Team Home Runs]
再一次,从最大到最小排序。
.txt文件的示例如下所示:
Team: Name: Avg:HR:
MILRyan Braun .31015
STLMatt Adams .28718
PITSterling Marte .26420
CINJoey Votto .30224
CUBAnthony Rizzo .27422
PITAndrew McCutchen .29522
MILAdam Lind .28013
以下类读取.txt文件并将其放入数组。
public class ReadTxt {
static String[] teamm = new String[20];
static String[] name = new String[20];
static int[] avg = new int[20];
static double[] homeRuns = new double[20];
static String teams;
static int i;
public void Players(String[] teamm, String[] name, int[] avg, double[] homeRuns){
String[] team = new String[20];
File txtFile = new File("C:\\Users\\Users Name\\Desktop\\homerun.txt");
try{
Scanner txtScan = new Scanner(txtFile);
while(txtScan.hasNext()){
for(i = 0; i < 20; i++){
teams = txtScan.nextLine();
team[i] = teams;
}
}
}
catch(FileNotFoundException e){
System.out.println("File not found" + txtFile);
}
for (i = 0; i < team.length; i++){
System.out.println(team[i]);
}
}
}
下一课是我的排序尝试:
public class Sort {
static String[] teamm = new String[20];
static String[] name = new String[20];
static int[] avg = new int[20];
static double[] homeRuns = new double[20];
private int index = 0;
private int US = 0;
static double[] homeRunArray;
public void Players(String[] teamm, String[] name, int[] avg, double[] homeRuns){
homeRunArray[index] = ReadTxt.homeRuns[index];
index++;;
US++;
}
public void selectionSort(){
double temp;
int min;
for(int i = 0; i < US-2; i++){
min = i;
for(int j=i+1; j<= US-1; j++){
if(min !=i){
temp = homeRunArray[i];
homeRunArray[i] = homeRunArray[min];
homeRunArray[min] = temp;
}
}
}
}
public void printArray(double[] homeRuns){
for(int i = 0; i < 20; i++){
System.out.print(homeRunArray[i]);
}
System.out.print("\n");
}
}
1楼
我没有收到您的问题,但我认为您有点陷入2D阵列问题中……
我建议您创建一个类并实现Comparable
(或使用Comparator
)。
像下面的代码或什至更好的代码,可以构成一个真正的Player
类。
这更容易理解。
public class Sorter {
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(new File("team"));
List<SortableLine> lines = new ArrayList<SortableLine>();
while(scanner.hasNext()) {
lines.add(new SortableLine(scanner.nextLine()));
}
Collections.sort(lines);
for(SortableLine line : lines) {
System.out.println(line.line);
}
} catch(FileNotFoundException e) {
System.err.println("File not found");
}
}
private static class SortableLine implements Comparable<SortableLine> {
private String sortCol;
private String line;
private SortableLine(String line) {
this.line = line;
this.sortCol = line.substring(24, 26);
}
public int compareTo(SortableLine other) {
return sortCol.compareTo(other.sortCol);
}
}
}