I am creating a leaderboard that is part of a game that I am working on. Basically, the code I have stores the user's name in the first column and the score associated with that user's name in the second column in a 2D array. It sorts the 2D array in descending order according to the score numbers in the second column. This is the code I have:
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();
}
This code is inside a while loop. The user has the option to see the leaderboard as many times as they want until the press the correct number to terminate the program. So the problem I have is when the user decides to view the leaderboard, it works the first time, but when the user wants to view the leaderboard a second time, the program crashes.
This is the error message I'm getting:
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)
How do I fix this so the user can view the leaderboard as many times as they want before they want to terminate the program?