c# - 从文件中读取时,索引超出了数组的范围
问题描述
我希望你们所有人都有美好的一天。所以我修复了我的程序的一个错误,但还有另一个错误:/
所以这是我创建并从文件中读取数据的代码:
void ReadData(string fileName, Branch[] branches)
{
string shopsName = null;
using (StreamReader reader = new StreamReader(@fileName))
{
string line = null;
line = reader.ReadLine();
if (line != null)
{
shopsName = line;
}
Branch tempBranches = TempBranch(branches, shopsName);
string address = reader.ReadLine();
string phoneNumber = reader.ReadLine();
while (null != (line = reader.ReadLine()))
{
string[] values = line.Split(';');
string facturer = values[0];
string model = values[1];
double capacity = double.Parse(values[2]);
string energyClass = values[3];
string assemblyType = values[4];
string color = values[5];
string attribute = values[6];
double cost = double.Parse(values[7]);
Fridges fridge = new Fridges(facturer, model, capacity, energyClass, assemblyType, color, attribute, cost);
tempBranches.fridges.AddFridge(fridge);
}
}
还有我使用 TempBranch 方法的代码。错误在这一行:if (branches[i].ShopsName == shopsName)
。希望你能帮助我,因为我昨天试图修复这个问题 30 分钟,但它仍然没有工作:D
private static Branch TempBranch(Branch[] branches, string shopsName)
{
for (int i = 0; i < MaxNumberOfFridges; i++)
{
if (branches[i].ShopsName == shopsName)
{
return branches[i];
}
}
return null;
}
解决方案
如果你用它替换MaxNumberOfFridges
它branches.Length
只会尝试找到一个在数组Branch
范围内的。branches
它不起作用的原因是因为您试图访问一个大于Length
数组的索引。
推荐阅读
- xamarin - 将数据从服务器插入 SQLite 数据库
- android - 新文件 Drawable 不可用我参考
- mysql - 当一个为空时按顺序组合两个结果列
- laravel - Laravel 5.7 按日期搜索
- material-ui - 如何覆盖选项卡的选定样式?
- java - 使用 mongoTemplate 在 Spring 中创建 mongo 查询
- postgresql - org.postgresql.util.PSQLException:错误:在 WHERE 中不允许设置返回函数
- python - 在python中动态创建嵌套字典
- python - 按升序合并 2 个排序列表
- reactjs - 更新 onClick 事件 plotly.js 上的范围滑块范围