Hey guys i'm new to java and this is the first time i'm posting a question on daniweb so please bear with me ...
I have made a quiz for a school project and its almost done save a high scoring mechanism.
What i want is first ask the user whether he/she would like to save the score and if so i call another function with the score (int) & the user's name (String) as parameters.
Now I want this function to save the scores and the respective username in a file in descending order and only the top 10 scores are to be saved thus i also want to see whether the user's score is good enough ...
i wrote a function using arrays, files and strings to do this but the problem is that only one name gets written and the rest remain blank ... and i've tried both the 'true' form of the file declaration as well as the one without it ... here's my code ...
public class Score()
{public static void score(int score, String name)
Score s=new Score();
FileWriter fw=new FileWriter("Scores.txt", true); //same thing happens even without 'true'
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
FileReader fr=new FileReader("Scores.txt");
BufferedReader br=new BufferedReader(fr);
String ns[]=new String [11];
int i, j;
for(i=0;i<11;i++) //initializing all elements to null
{ns="";
}
String newScore=s.codeDecode(score); //making sure that the scores have equal no of
//digits so that i can use compareTo()
ns[10]=newScore + "\t\t\t" + name;
String text="", temp="";
i=0;
while((text=br.readLine())!=null)
{System.out.println(ns);
ns=text.toString(); //reading the contents of the file and storing each line in
i++; //a diff. element so that each contains a username & score
if(i>9)
break;
}
for(i=0;i<10;i++)
{for(j=i+1;j<11;j++)
{if((ns.compareTo(ns[j])<0)) //if score in ns is lower than that in ns[j]
{temp=ns.toString(); //i swap the 2 elements
ns=ns[j].toString(); //thus the array comes in descending order
ns[j]=temp;
}
}
}
for(i=0;i<10;i++)
{pw.println(ns); //i print the elements of the array on to the file
}
pw.close();
}
public static String codeDecode(int score)
{int i=0, d, copy=score;
while(copy!=0)
{copy/=10; //counting no of digits in score
i++;
}
int z=3-i; //Since maximum score possible is 999
String newScore="";
for(i=1;i<=z;i++)
{newScore="0" + newScore; //appending equivalent no of zeros
}
newScore=newScore + score;
return newScore;
}
I dont see why this function isnt working but to give you a better idea of the problem here's an example
Say, A scores 100, then B scores 75, then C scores 120
Ideally, the file should get written thus
C 120
A 100
B 75
However what actually happens is
C 120
thats it
and its not because c is the maximum value
Whatever values i enter at the end only that value gets stored .
So please if there's anyone who could help me out.
This project's due in a week and my exams start in a week as well so i really need to finish it fast.
Thanks.