【发布时间】: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 类型