c# - Index out of Range exception in arrays -
i continuously getting out of range exception in code. went debug mode , found giving error zeroth index itself. appreciated.
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 value."); inputvalue = console.readline(); console.writeline("enter number of forbidden words."); numberofforbiddenwords = int.parse(console.readline()); console.writeline("please enter forbidden words"); (int = 0; < numberofforbiddenwords; i++) forbiddenwords[i] = console.readline(); } public static void removingwords() { for(int =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() { (int = 0; < numberofforbiddenwords; i++) stargenerated[i] = ""; (int k = 0; k < numberofforbiddenwords; k++) (int = 0; < forbiddenwords[k].length-1; i++) stargenerated[k] = stargenerated[k] + '*'; } } } the stargenerator() loops create error.
this line:
public static string [] stargenerated = new string[numberofforbiddenwords]; ... executed when class initialized. happen while numberofforbiddenwords still 0, i.e. long before line executed:
numberofforbiddenwords = int.parse(console.readline()); so when call stargenerator, unless numberofforbiddenwords still 0, you're going trying access invalid indexes.
i try avoid these static variables - suspect they're confusing in terms of when initialization occurring.
Comments
Post a Comment