I am trying to read a csv file that contains the names and scores in one line. My code works fine if the csv has exactly 20values(10names and 10 scores). Im having a difficulty making it work if the csv file is empty or has less than 20 values. My code reads the csv in an array and then stores the names and scores in two different arrays. Then it compares if a new player has a score greater than ones already stored in the csv file, if it is then it replaces it and then stores all updated names and scores in one array. The csv file can have a maximum of 10 names and 10 scores and the minimum can be empty csv.
public class CompareLeaderboard {
public static void main(String[] args) {
CompareLeaderboard user = new CompareLeaderboard();
user.run();
}
public void run() {
String csvFileLoc = "/Documents/leaderboard.csv";
BufferedReader br = null;
String line = "";
String commaSeparator = ",";
int[] userScore = new int[10];
String[] userName = new String[10];
String[] userInfo = new String[20];
int k = 0;
int h =0;
int z = 10;
int tempS;
String tempN;
int playerScore = 50;
String playerName = "Matt";
boolean breaking = false;
try {
//int a = 1;
br = new BufferedReader(new FileReader(csvFileLoc));
while ((line = br.readLine()) != null) {
// use comma as separator
//if(a==1){
String[] userDetails = line.split(commaSeparator);
for(int j =0; j<20; j = j+2){
userName[k] = userDetails[j];
int foo = Integer.parseInt(userDetails[j+1]);
userScore[k] = foo;
k++;
}
// }
}
//a++;
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//checking
for(int i = 0; i <10 ; i++){
if(userScore[i] < playerScore) {
if(breaking == false){
z = i;
breaking = true;
}
}
//else if(i==9 && userScore[i] > playerScore){
//}
}
//storing
if(z<10) {
for(int j = z; j< userName.length; j++){
tempN = userName[j];
tempS = userScore[j];
userName[j] = playerName;
userScore[j] = playerScore;
playerName = tempN;
playerScore = tempS;
}
}
for(int i = 0; i < userName.length; i++){
System.out.println(userName[i] + " = " + userScore[i]);
}
for(int s = 0; s<20; s = s+2) {
userInfo[s] = userName[h];
String foo = String.valueOf(userScore[h]);
userInfo[s+1] = foo;
h++;
}
for(int i = 0; i < userInfo.length; i++){
System.out.println(userInfo[i] + ", ");
}
}
}