【发布时间】:2019-02-05 21:21:25
【问题描述】:
我一直在做一个测验,并想实施一个排行榜。排行榜应该显示用户的名字,分数
我检查了它是否正在识别文件,当我删除分数时它工作正常。当我以所有其他形式在标签上显示分数时,分数工作正常。
公共部分类frmLeaderboard:表格
{enter code here
//设置播放器列表
列出玩家 = new List();
public frmLeaderboard()
{
//Setup form
InitializeComponent();
dgLeaderboard.ColumnCount = 3;
dgLeaderboard.Columns[0].Name = "Player Name";
dgLeaderboard.Columns[1].Name = "Score";
dgLeaderboard.Columns[2].Name = "Level";
SaveScores();
GetPreviousPlayers();
}
private void GetPreviousPlayers()
{
//searches for file and loads score
if(File.Exists("previousplayers.txt"))
{
LoadScores();
}
dgLeaderboard.Sort(dgLeaderboard.Columns[1], ListSortDirection.Descending);
}
private void LoadScores()
{
if (File.Exists("previousplayers.txt"))
{
//Loads the score
var playerScores = File.ReadAllLines("previousplayers.txt");
if (playerScores.Length > 0)
{
//bring in the players to the grid
foreach (var players in playerScores)
{
var splitDetails = players.Split('~');
dgLeaderboard.Rows.Add(splitDetails[0], Convert.ToInt32(splitDetails[0]), splitDetails[2]);
}
}
else
{
HideGrid();
}
}
}
private void SaveScores()
{
FileStream fileStream = new FileStream("previousplayers.txt", FileMode.Append, FileAccess.Write);
StreamWriter streamWriter = new StreamWriter(fileStream);
//Seperate the username, score and level
try
{
foreach(var player in players)
{
streamWriter.WriteLine(player.Username + "~" + player.Score + "~" + player.Level);
}
}
catch(Exception)
{
MessageBox.Show("Error Loading the scores", "Please try again");
}
finally
{
streamWriter.Close();
fileStream.Close();
}
}
private void HideGrid()
{
//Sets the grid to invisible
dgLeaderboard.Visible = false;
}
}
在我使用此代码之前的表单中
string filePath = "previousplayers.txt";
FileStream aFile;
StreamWriter sw;
try
{`enter code here`
if (!File.Exists(filePath))
{
aFile = new FileStream(filePath, FileMode.Create, FileAccess.Write);
}
else
{
aFile = new FileStream(filePath, FileMode.Append, FileAccess.Write);
}
sw = new StreamWriter(aFile);
sw.WriteLine(frmStart.Player.Username + "~" + frmStart.Player.Score + "~" + frmStart.Player.Level);
sw.Close();
aFile.Close();
}
catch (Exception ex)
{
MessageBox.Show("User's details have not been saved", "Error Occurred");
}
它因错误而崩溃:Exception Unhandled, System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
在这一行 dgLeaderboard.Rows.Add(splitDetails[0], Convert.ToInt32(splitDetails[0]), splitDetails[2]);
块引用
【问题讨论】:
-
发生该错误是因为您向数组索引器提供的索引太大(>=数组大小)或负数。
-
另外,请注意您不需要检查
File.Exists(filePath)。如果文件不存在,FileMode.Append将创建该文件。 +Convert.ToInt32(splitDetails[0]):splitDetails[0]在这里是一个字符串,包含player.Username,因为:streamWriter.WriteLine(player.Username + "~" (...)。除非您混合不同的版本程序。