简体   繁体   English

用Java排序2d字符串数组

[英]Sorting a 2d String Array in Java

I created a 2d-array in Java for a project that reads in a file, processes the data, and the prints it back out. 我在Java中为一个项目创建了一个2d数组,该项目读入文件,处理数据并将其打印出来。 The only problem I am having is trying to sort the 2d-array alphabetically. 我遇到的唯一问题是尝试按字母顺序对2d阵列进行排序。

This is an example of the file input: 这是文件输入的示例:

2011 Regular Season
Boston 162 5710 875 1600 352 35 203
NY_Yankees 162 5518 867 1452 267 33 222
Texas 162 5659 855 1599 310 32 210
Detroit 162 5563 787 1540 297 34 169
St.Louis 162 5532 762 1513 308 22 162
Toronto 162 5559 743 1384 285 34 186
Cincinnati 162 5612 735 1438 264 19 183
Colorado 162 5544 735 1429 274 40 163
Arizona 162 5421 731 1357 293 37 172
Kansas_City 162 5672 730 1560 325 41 129

And this is an example of what the output looks like: 这是输出结果的示例:

2011 Regular Season
====================
Boston:     .280 .461
NY_Yankees: .263 .444
Texas:      .283 .460
Detroit:    .277 .434
St.Louis:   .273 .425
Toronto:    .249 .413
Cincinnati: .256 .408
Colorado:   .258 .410
Arizona:    .250 .413
Kansas_City:.275 .415
====================
Big Ten Av: .266 .428

My goal is to have the team names sorted alphabetically. 我的目标是让团队名称按字母顺序排序。 I have tried using the Array.sort() method as well as using a Comparator but nothing has worked. 我已经尝试使用Array.sort()方法以及使用Comparator但没有任何工作。 I will include the working code that I have now and any help would be great! 我将包含我现在的工作代码,任何帮助都会很棒!

package problem_1;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Comparator;

public class sluggers2 {

static String specificstat[][] = new String[1000][1000]; //Create a 2-dimensional array with limits of 1000
static DecimalFormat df = new DecimalFormat(".###");//Variable to round the integers to 3 decimal places

public static void main(String args[]) { //Main method
    execute(); //Call on the function "execute" and execute it
    baseballstats(1);
}

public static String[][] execute() {
    int line = 0;
    try {
        BufferedReader in = new BufferedReader(new FileReader("stuff/input_sluggers.txt"));

        String str;
        while ((str = in.readLine()) != null) {
            if (str.trim().length() == 0) {
                continue; // Skip blank lines
            }
            specificstat[line] = str.split(" ");
            line++;
        }
        in.close();
    } catch (IOException e) {
        System.out.println("Can not open or write to the file.");
    }
    return specificstat;
}

public static void baseballstats(int teamnumber) {
    double batting_average, slugging_average = batting_average = 0;

            //Arrays.sort(specificstat[0]);
            //Tried sorting the first dimension but it didn't work

    System.out.println(specificstat[0][0] + " " + specificstat[0][1] + " " + specificstat[0][2]);
    System.out.println("====================");

    while (teamnumber <= 10) {

        double B = Integer.parseInt(specificstat[teamnumber][5]);
        double C = Integer.parseInt(specificstat[teamnumber][6]);
        double D = Integer.parseInt(specificstat[teamnumber][7]);
        double A = Integer.parseInt(specificstat[teamnumber][4]) - (B + C + D);

        double slug_avg = ((A + 2*B + 3*C + 4*D) / Integer.parseInt(specificstat[teamnumber][2]));
        double y = Integer.parseInt(specificstat[teamnumber][4]), z = Integer.parseInt(specificstat[teamnumber][2]), bat_avg = y / z;

        slugging_average = slugging_average + slug_avg;
        batting_average = batting_average + bat_avg;

        double hits = Integer.parseInt(specificstat[teamnumber][4]);
        double at_bats = Integer.parseInt(specificstat[teamnumber][2]);

        String batting = df.format(hits / at_bats), slugging = df.format(slug_avg);

        if (slugging.length() == 3)
            slugging = slugging + "0";

        if (batting.length() == 3)
            batting = batting + "0";

        System.out.println(specificstat[teamnumber][0] + ":  " +  "\t" + batting + " " + slugging);
        teamnumber++;
    }

    String big_ten_av = "\t" + df.format(batting_average / 10) + " "+ df.format(slugging_average / 10);

    System.out.println("====================");
    System.out.print("Big Ten Av: "); System.out.print(big_ten_av);
}
}

I'm relatively new to coding so any help would be much appreciated. 我对编码比较陌生,所以任何帮助都会非常感激。

You need something like this: 你需要这样的东西:

Arrays.sort( specificstat, new Comparator<String[]> {
    public int compare( String[] s1, String[] s2 ) {
        return s1[0].compareTo(s2[0]);
    }
} );

Which basically says to sort the inner arrays of specificstat by comparing the first element of each of the inner arrays... 这基本上是通过比较每个内部数组的第一个元素来对特定状态的内部数组进行排序...

An alternative solution to Lucas' is to eliminate the 2d array entirely, and use an array of some class, say: Lucas'的另一种解决方案是完全消除2d数组,并使用某个类的数组,比如说:

class TeamRecord implements Comparable {
  public String teamName;
  public ArrayList<Integer> stats;

  int compareTo(TeamRecord other) {
    return teamName.compareTo(other.teamName);    
  }

}

And change your: 并改变你的:

static String specificstat[][] = new String[1000][1000];

to: 至:

static TeamRecord specificstat[] = new TeamRecord[1000];

Then Array.sort(specificstat) will sort based on teamName. 然后Array.sort(specificstat)将根据teamName进行排序。

The advantage of this approach is that it makes your data more clear, since the team name is really a different kind of thing than the stats; 这种方法的优点是它可以使您的数据更加清晰,因为团队名称实际上与统计数据不同; here the types make that immediately clear. 这里的类型立即清楚。

I've omitted code that will populate an array of that datatype, but I think you can figure it out. 我省略了将填充该数据类型数组的代码,但我认为你可以搞清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM