不明白为什么 for 循环超出范围

本文关键字:范围 循环 for 明白 为什么 | 更新日期: 2023-09-27 18:36:39

我正在学习 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();  
        }

不明白为什么 for 循环超出范围

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

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

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

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

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

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

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();

查看

 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 += " ";
    }
}
}