我正在学习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();
}
while ((searchSentence[i] != ' ') && (searchSentence.Length > i))
考虑一下您的阅读方式(从树林的右到左)正在影响您编写代码的方式。无论是&&操作数的顺序还是在Length测试中,此代码都是向后的。因此,不会利用&&运算符的短路行为。可能很难学习,这是您必须要做的事情。
避免出现以下异常:
while ((i < searchSentence.Length) && (searchSentence[i] != ' '))
这样可以确保searchSentence [i]不会抛出IndexOutOfRangeException。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句