【问题标题】:Cant understand why the for loop get out of range无法理解为什么 for 循环超出范围
【发布时间】:2015-01-08 10:04:20
【问题描述】:

我正在学习 c#,并且有家庭作业在控制台应用程序中制作简单的字典。 我编写了所有代码,它应该可以正常工作,但是在其中一个 for 循环中,程序会抛出 Error:System.IndexOutofRange。 我尝试了我所知道的一切(我只是初学者,所以我知道的不多)但它总是给出错误。 该程序的主要思想是用户必须输入他希望使用的单词数量,然后以他的语言(我是希伯来语,所以程序中是希伯来语)和英语输入单词,并将单词保存在两个不同的数组中,但是在同一个索引中。然后程序要求用户用他的语言输入句子,然后程序在句子上运行找到单词(每次程序看到空格它都会开始一个新单词),然后使用另一个 for 循环它在希伯来语数组中查找,如果它找到匹配的单词在同一索引中但在英文数组中,如果没有找到它会写入原始单词。

 static void Main(string[] args)
    {
        Console.WriteLine("Enter the number of words you wish to use");
        int wordsNumber = int.Parse(Console.ReadLine());

        string[] hebrew = new string[wordsNumber];
        string[] english = new string[wordsNumber];

        for (int i = 0; i < wordsNumber; i++)
        {
            Console.WriteLine("Enter word in Hebrew.");
            hebrew[i] = Console.ReadLine();
            Console.WriteLine("Now enter the translate of {0} in English.",hebrew[i]);
            english[i] = Console.ReadLine();
        }

        Console.WriteLine("Now enter the sentence that you want to translate..and press ENTER");
        string searchSentence = Console.ReadLine();
        string translateWord = "";
        string result = "";
        while(searchSentence != "stop")
        {

            for (int i = 0; i < searchSentence.Length;i++ )
            {
                translateWord = "";
                while ((searchSentence[i] == ' ')&&(searchSentence.Length > i))//Skip the spaces      in the start of the sentence
                    i++;
                while ((searchSentence[i] != ' ') && (searchSentence.Length > i))//Here is the problem when with the OutOfRnge
                {
                    translateWord += searchSentence[i];
                    i++;
                }
                for(int j = 0;j<hebrew.Length ;j++)
                {
                    if (translateWord == hebrew[j])
                    {
                        result += english[j];
                    }
                    else
                    {
                        result += translateWord[i];
                    }
                    result += " ";
                 }
            }
            Console.WriteLine(result);

            Console.WriteLine("Enter new sentence for translate or enter 'stop' to EXIT the  programm");
            searchSentence = Console.ReadLine();  
        }

【问题讨论】:

  • 哪一行给出了错误
  • 您的代码看起来很混乱,但是如果 Length == i 查找 searchSentence[i] 时很容易超出范围
  • 我在代码中写了注释(第 38 行)
  • 如果长度为 8,则应使用 searchSentence.Length > (i-1) 更改条件,数组从 0 变为 7
  • 我只是初学者,所以我只知道使用和能够使用数组 for/while 循环和 int/double/string/char/bool vars 类型

标签: c# arrays for-loop


【解决方案1】:
   while ((searchSentence[i] != ' ') && (searchSentence.Length > i))

考虑一下,您习惯于阅读的方式(从右到左)正在影响您编写代码的方式。此代码是向后的,无论是 && 操作数的顺序还是长度测试。因此没有利用 && 运算符的 短路 行为。可能很难忘记,你必须努力。

通过以下方式避免此异常:

   while ((i < searchSentence.Length) && (searchSentence[i] != ' '))

确保 searchSentence[i] 不会抛出 IndexOutOfRangeException。

【讨论】:

  • 但是您稍后可以在代码中得到相同的预期,并在这一行使用 yhis result += translateWord[i];
  • 我绝对认为从右到左阅读的期望可能是这里的真正问题 +1,
  • 这也是倒退,是“相信”:)
【解决方案2】:

您的代码非常混乱,很难判断错误在哪里。但是,您最好构建一个充满翻译的字典,然后使用它。我省略了错误处理供您扩展,但这里有一个完全相同的示例 - 但使用字典

Dictionary<string, string> words = new Dictionary<string, string>();

Console.WriteLine("Enter the number of words you wish to use");
int wordsNumber = int.Parse(Console.ReadLine());

for (int i = 0; i < wordsNumber; i++)
{
    Console.WriteLine("Enter word in Hebrew.");
    string hebrew = Console.ReadLine();
    Console.WriteLine("Now enter the translate of {0} in English.", hebrew);
    string english = Console.ReadLine();

    words.Add(hebrew, english);
}

Console.WriteLine("Now enter the sentence that you want to translate..and press ENTER");
string searchSentence = Console.ReadLine();

string[] splitSentence = searchSentence.Split(new char[]{' '});
string result = "";

foreach (string s in splitSentence)
    result += string.Format("{0} ", words[s]);

Console.WriteLine(result);
Console.ReadLine();

【讨论】:

  • 我确定这是更好的解决方法,但我仍然无法使用这些方法(字典/拆分/添加/格式)我什至仍然不知道他们做了什么。
  • @satis - 那是给你研究的......字典是c#中的一种类型,它构造了一种键(这里是希伯来语)和值(英语)的表,这样就很容易了并快速找到所需的值。 MSDN 是一个非常适合您研究的网站,您可以在 google 上搜索“MSDN 方法/类/类型名称”以快速找到结果...例如“MSDN 字典”返回 this 作为第一个结果
【解决方案3】:

看着

 while(searchSentence != "stop")
    {

        for (int i = 0; i < searchSentence.Length;i++ )
        {
            translateWord = "";
            while ((searchSentence[i] == ' ')&&(searchSentence.Length > i))//Skip the spaces      in the start of the sentence
                i++; //updated here and used on nex line when i could be greater than SearchSentence.Length now
            while ((searchSentence[i] != ' ') && (searchSentence.Length > i))//Here is the problem when with the OutOfRnge
            {
                translateWord += searchSentence[i];
                i++; // updated here
            }
            for(int j = 0;j<hebrew.Length ;j++)
            {
                if (translateWord == hebrew[j])
                {
                    result += english[j];
                }
                else
                {
                    result += translateWord[i];
                }
                result += " ";
             }
        }

您在 for 循环内增加 i。如果它等于或大于searchSentence.Length,那么你使用它会抛出你得到的错误

编辑以修复从这里进行此更改

 for (int i = 0; i < searchSentence.Length;i++ )
        {
            translateWord = "";
            while ((searchSentence[i] == ' ')&&(searchSentence.Length > i))//Skip the spaces      in the start of the sentence
                i++;
            while ((searchSentence[i] != ' ') && (searchSentence.Length > i))//Here is the problem when with the OutOfRnge
            {
                translateWord += searchSentence[i];
                i++;
            }
            for(int j = 0;j<hebrew.Length ;j++)
            {
                if (translateWord == hebrew[j])
                {
                    result += english[j];
                }
                else
                {
                    result += translateWord[i];
                }
                result += " ";
             }
        }

到这里

for (int i = 0; i < searchSentence.Length;i++ )
{
if(((searchSentence[i] != ' ')&&(searchSentence.Length > i)))
{
    while ((searchSentence[i] != ' ') && (searchSentence.Length > i))//Here was the problem when with the OutOfRnge
    {
            translateWord += searchSentence[i];
            i++; // updated here
        if(i>=searchSentence.Length)
        {
            break;
        }
    }
    if(i>=searchSentence.Length)
    for(int j = 0;j<hebrew.Length ;j++)
    {
        if (translateWord == hebrew[j])
        {
            result += english[j];
        }
        else
        {
            result += translateWord[i];
        }
        result += " ";
    }
}
}

【讨论】:

  • 答案到底是什么?我没看到。
  • 他们在 for 循环中更新 for 循环的增量器,然后使用它来访问数组,如果它在循环的最后一个滴答声上,然后他们将它增加 1,然后抛出越界错误
  • 是的,我得到了那个部分,但是你如何解决它?你没有给出解决方案,只是一个理由。
  • 最好也提供一个解决方案。没有解决方案的答案对我来说有点空洞。
  • @satis:手工计算如果你的句子以空格字符结尾会发生什么。在这种情况下,您的代码会将 i 递增到数组边界之外。您还可以通过使用string 类型的Trim() 方法来避免字符串空格的开始/结束。
猜你喜欢
  • 1970-01-01
  • 2011-09-07
  • 2018-12-17
  • 1970-01-01
  • 2019-04-17
  • 1970-01-01
  • 2013-09-28
  • 2013-11-25
  • 2017-08-09
相关资源
最近更新 更多