C#二进制搜索始终返回未处理的异常或没有结果...为什么?

时间:2018-09-28 10:29:13

标签: c# binary-search unhandled-exception

代码:

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 

0 个答案:

没有答案