使用Java中的列对2D字符串数组进行排序的问题

时间:2018-04-06 03:17:51

标签: java arrays string sorting

我正在创建一个排行榜,这是我正在制作的游戏的一部分。基本上,我将代码存储在第一列中的代码以及与该用户名称相关联的分数存储在2D数组的第二列中。它根据第二列中的得分数按降序对2D数组进行排序。这是我的代码:

String line = null;
String lineCounter = null;

try {
    BufferedReader br = new BufferedReader(new FileReader("scores.txt"));
    while ((lineCounter = br.readLine()) != null) {
        lineCount++;
    }

    String[][] scores = new String[lineCount][2];
    int x = 0;

    BufferedReader BR = new BufferedReader(new FileReader("scores.txt"));
    while ((line = BR.readLine()) != null) {
        String[] nums = line.split(": ");
        scores[x][0] = nums[0];
        scores[x][1] = nums[1];
        x++;
    }

    Arrays.sort(scores, new Comparator<String[]>() {
        @Override
        public int compare(final String[] first, final String[] second) {
            // TODO Auto-generated method stub
            return Double.valueOf(second[1]).compareTo(
                Double.valueOf(first[1])
            );
        }
    });
    String[][] theCopy = Arrays.copyOf(scores, scores.length);

    for (int i = 0; i < theCopy.length; i++) {
        System.out.print((i + 1) + ". ");
        for (int j = 0; j < 2; j++) {
            if(j == 0) System.out.print(theCopy[i][j] + ": ");
            if(j == 1) System.out.print(theCopy[i][j]);
        }
        System.out.println();
    }
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

此代码位于while循环中。用户可以选择多次查看排行榜,直到按下正确的号码终止程序。所以我遇到的问题是当用户决定查看排行榜时,它会第一次运行,但是当用户想要第二次查看排行榜时,程序会崩溃。

这是我收到的错误消息:

Exception in thread "main" java.lang.NullPointerException
    at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
    at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
    at java.lang.Double.parseDouble(Unknown Source)
    at java.lang.Double.valueOf(Unknown Source)
    at prjTicTacToe.TicTacToe$1.compare(TicTacToe.java:200)
    at prjTicTacToe.TicTacToe$1.compare(TicTacToe.java:1)
    at java.util.TimSort.binarySort(Unknown Source)
    at java.util.TimSort.sort(Unknown Source)
    at java.util.Arrays.sort(Unknown Source)
    at prjTicTacToe.TicTacToe.main(TicTacToe.java:195)

如何解决此问题,以便用户可以在他们想要终止程序之前多次查看排行榜?

0 个答案:

没有答案