[英]Index out of Range exception in arrays
我在代碼中不斷超出范圍異常。 我進入調試模式,發現它為第零個索引本身提供了錯誤。 任何幫助將不勝感激。
namespace StringTest7
{
class Program
{
static void Main(string[] args)
{
Input();
StarGenerator();
RemovingWords();
Console.ReadKey();
}
public static string [] forbiddenWords = new string [10];
public static int numberOfForbiddenWords;
public static string inputValue;
public static void Input()
{
Console.WriteLine("Enter the value.");
inputValue = Console.ReadLine();
Console.WriteLine("Enter the number of forbidden words.");
numberOfForbiddenWords = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the forbidden words");
for (int i = 0; i < numberOfForbiddenWords; i++)
forbiddenWords[i] = Console.ReadLine();
}
public static void RemovingWords()
{
for(int i =0;i<numberOfForbiddenWords;i++)
{
for(int j = 0; j< inputValue.Length - 1; i++)
{
inputValue.Replace(forbiddenWords[i],
starGenerated[i]);
}
}
Console.WriteLine(inputValue);
}
public static string [] starGenerated = new string[numberOfForbiddenWords];
public static void StarGenerator()
{
for (int i = 0; i < numberOfForbiddenWords; i++)
starGenerated[i] = "";
for (int k = 0; k < numberOfForbiddenWords; k++)
for (int i = 0; i < forbiddenWords[k].Length-1; i++)
starGenerated[k] = starGenerated[k] + '*';
}
}
}
StarGenerator()循環會產生錯誤。
這行:
public static string [] starGenerated = new string[numberOfForbiddenWords];
...在類初始化時執行。 當numberOfForbiddenWords
仍然為0時,即在執行此行之前很久,就會發生這種情況:
numberOfForbiddenWords = int.Parse(Console.ReadLine());
因此,當您調用StarGenerator
,除非numberOfForbiddenWords
仍然為 0,否則您將嘗試訪問無效索引。
我會盡量避免使用所有這些靜態變量-我懷疑它們會在初始化發生時使您感到困惑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.