我想读取包含一行中的名称和分数的csv文件。我的代码工作正常,如果csv恰好有20个值(10个名称和10个分数)。如果csv文件为空或者值小于20,Im有困难。我的代码读取数组中的csv,然后将名称和分数存储在两个不同的数组中。然后比较新玩家的分数是否大于已存储在csv文件中的分数,如果是,则替换它,然后将所有更新的名称和分数存储在一个数组中。 csv文件最多可以有10个名字和10个分数,最小值可以是空的csv。如果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] + ", ");
}
}
}
简单的答案,使用一个真正的CSV解析库。例如,[OpenCSV](http://opencsv.sourceforge.net/)非常出色。 – 2014-11-23 10:53:55