代码:
using System;
using System.IO;
using System.Collections.Generic;
class MainClass {
public static void Main (string[] args) {
Console.WriteLine ("Get Random Names");
// Read every line in the file.
List<string> nameList = new List<string>();
using (StreamReader reader = new StreamReader("test.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
nameList.Add(line);
}
}
nameList.Sort();
int middleValue = (nameList.Count + 1) / 2;
Console.WriteLine("Enter a name to search for.");
String name = Console.ReadLine();
bool nameNotFound = true;
while (nameNotFound) {
if (String.Compare(nameList[middleValue], name) < 0) {
middleValue = middleValue / 2;
}
else if (String.Compare(nameList[middleValue], name) > 0) {
middleValue = middleValue + (middleValue / 2);
}
else if (String.Compare(nameList[middleValue], name) == 0) {
Console.WriteLine("Name " + name + " was found.");
nameNotFound = false;
}
}
}
}
错误: 该程序总是不执行任何操作或返回未处理的异常...
Unhandled Exception:
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at MainClass.Main (System.String[] args) [0x000d8] in <d6354b39640d4dfd8d3edafa3e7807ee>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at MainClass.Main (System.String[] args) [0x000d8] in <d6354b39640d4dfd8d3edafa3e7807ee>:0