我如何继续使用C#中的字典,该字典读取一个简单的文本文件,其中包含作者书中的按城镇排序问题



我有一个简单的文本文件,可以读取姓名、城市和手机号码。下面的代码显示了字典、数组和C#编程。SortedDictionary是按关键字排序的,这里是"城市",明白了吗?下面的代码给我带来了一个索引越界错误,我需要帮助修复它。我的错误在这里:

string name = entry[0].Trim();  
string town = entry[1].Trim(); //index out of bounds error    
string phone = entry[2].Trim();

我的文本文件未排序:

Names
Cities
Cell Phone Numbers
Kennedy
Nairobi
1-234-567-8911
Silas
Lusaka
2-345-678-9112
Joseph
Jerusalem
3-456-789-1112
Diana
Kisumu
4-567-891-2345
Winston
Migori
5-678-912-3456

代码如下:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sort_Dictionary_Script
{
class Program
{
static void Main(string[] args)
{
//Read the file and build the phone book
SortedDictionary<string, SortedDictionary<string, string>>
phonesByTown = new SortedDictionary<string, SortedDictionary<string, string>>();
StreamReader reader = new StreamReader("PhoneBook.txt");
using (reader)
{
int x = 1;
while (x <= 4)
{
x++;
string line = reader.ReadLine();
if (line == null)
{
break;
}                  
string[] entry = line.Split(new char[] { '|' });
string name = entry[0].Trim();
string town = entry[1].Trim();
string phone = entry[2].Trim();
SortedDictionary<string, string> phoneBook;
// When a program often has to try keys that turn out not to
// be in the dictionary, TryGetValue can be a more efficient
// way to retrieve values.
if (!phonesByTown.TryGetValue(town, out phoneBook))
{
//This town is new. Create a phone book for it.
phoneBook = new SortedDictionary<string, string>();
phonesByTown.Add(town, phoneBook);
}
phoneBook.Add(name, phone);

}
}
//Print the phone book by towns
foreach (string town in phonesByTown.Keys)
{
Console.WriteLine("Town " + town + ":");
SortedDictionary<string, string> phoneBook = phonesByTown[town];
foreach (var entry in phoneBook)
{
string name = entry.Key;
string phone = entry.Value;
Console.WriteLine("t{0} - {1}", name, phone);
}
}
}
}
}

你能告诉我如何修复索引越界错误吗?我花了一些时间四处阅读,但仍然不明白。我需要做些什么才能在这方面做得更好?我正在读一本书中的代码,书中有这个代码,但代码不起作用。我是自学成才的。

最有可能的问题是文本文件中的某一行不能满足您的格式要求。即文件中的某一行不包含两个|字符。您可以通过插入支票跳过这些行

if(entry.Length < 3){
// continue, or use some other error handling
}

我建议你阅读埃里克·利珀特的《如何调试小程序》。像这样的错误很常见,但使用调试器也应该很容易找到。如果您在visual studio调试器中运行程序,它应该在异常处停止,从而允许您检查异常以及导致异常的任何相关变量。还有一个异常设置对话框,可以用于在抛出异常时中断,即使已处理异常。

最新更新