Reputation: 11
So im trying to write a program in c# that reads two files that have 11 names in one and 11 numbers in the other, they're supposed to correspond to a high-score leader board and the users name, i have already got the read and write files part of the code done and it's all fine but the problem comes from my bubble sort (which i have taken from another stack overflow question) and my outputting of the table, every single time i run through it again and have a new users data be input it will put a blank statement with no name and 0 time at the top, every other part of my code works except for this part. If you need more parts of the code i can send more just ask.
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
int temp = 80085;
string tenp = "test";
for (int write = 0; write < highscoreval.Length; write++)
{
for (int sort = 0; sort < highscoreval.Length - 1; sort++)
{
if (highscoreval[sort] > highscoreval[sort + 1])
{
temp = highscoreval[sort + 1];
highscoreval[sort + 1] = highscoreval[sort];
highscoreval[sort] = temp;
tenp = highnamestr[sort + 1];
highnamestr[sort + 1] = highnamestr[sort];
highnamestr[sort] = tenp;
}
}
}
for (int i = 0; i < highscoreval.Length; i++)
Console.Write(highscoreval[i] + " ");
Console.WriteLine();
Console.WriteLine("Rank || Name || Time");
for (int k = 1; k < length; k++)
{
Console.Write(k + " || " + highnamestr[k] + " || " + highscoreval[k]);
Console.WriteLine();
}
Console.WriteLine();
Ive tried many different ways of outputting the table and sorting the data but nothing seems to be able to get rid of the blank statements appearing
it should output all of the stored data in a nice table and have it all sorted by the end but it usually ends up being sorted and looking nice but having a blank user with 0ms time.
Upvotes: -1
Views: 62
Reputation: 6312
I think the problem is here:
for (int k = 1; k < length; k++)
{
Console.Write(k + " || " + highnamestr[k] + " || " + highscoreval[k]);
Console.WriteLine();
}
Why are you running from 1 to some undefined length
? The array starts a 0, and apparently you've made it too long and calculated length
wrong.
The code should be:
for (int k = 0; k < highnamestr.Length; k++)
{
Console.Write((k+1) + " || " + highnamestr[k] + " || " + highscoreval[k]);
Console.WriteLine();
}
I've checked it and it works (I set the names to the string version of the score):
Rank || Name || Time
1 || 9 || 9
2 || 11 || 11
3 || 50 || 50
4 || 240 || 240
5 || 649 || 649
6 || 770 || 770
7 || 771 || 771
8 || 800 || 800
But as @Cid suggests, there are more elegant ways of doing this.
Upvotes: 0