Results 1 to 2 of 2

Thread: System.IndexOutOfRangeException

  1. #1
    Join Date
    Dec 1969

    Default System.IndexOutOfRangeException

    I have been trying hard to solve this problem but it kept giving me this "System.IndexOutOfRangeException" Can anyone help?<BR><BR>using System;<BR>class testmulti2<BR>{<BR> public static void Main()<BR> {<BR> string[] StudentName=new string[12]{"Mary","Roy","Sam","Rose","George","Meiling","Har ry","Sandy","Francis","Peter","Jolie","David"};<BR > double[][]cpa=new double[12][];<BR><BR> cpa[0]=new double[]{3,0,4,5};<BR> cpa[1]=new double[]{1,4,2,5};<BR> cpa[2]=new double[]{5,1,4,3};<BR> cpa[3]=new double[]{1,3,1,1};<BR> cpa[4]=new double[]{4,3,5,5};<BR> cpa[5]=new double[]{5,0,4,5};<BR> cpa[6]=new double[]{5,2,5,5};<BR> cpa[7]=new double[]{5,3,2,5};<BR> cpa[8]=new double[]{1,1,3,45};<BR> cpa[9]=new double[]{3,4,4,5};<BR> cpa[10]=new double[]{4,2,4,3};<BR> cpa[11]=new double[]{2,4,4,5};<BR><BR> int a;<BR> double[]cpaAverage=new double[12];<BR> for(a=0;a&#060;12;a++)<BR> cpaAverage[a]=(cpa[a][0]+cpa[a][1]+cpa[a][2]+cpa[a][3]);<BR><BR> Console.WriteLine("{0}
    ",cpaAverage[a]);<BR> Console.WriteLine("------------------------------------------------------------------");<BR><BR> }<BR> <BR> <BR> }

  2. #2
    Join Date
    Dec 1969

    Default Brace yourself for this....

    You need to enclose all of the statements underneath the loop in a compound statement by enclosing them inside braces.<BR><BR> for(a=0;a&#060;12;a++) {<BR> // compound statements go here<BR> }<BR><BR>At the moment the computer is interpreting your code like so:<BR><BR> for(a=0;a&#060;12;a++) <BR> cpaAverage[a]=(cpa[a][0]+cpa[a][1]+cpa[a][2]+cpa[a][3]); <BR><BR> // Try putting in some debug code here...<BR> Console.WriteLine("Value of a is {0}", a) ;<BR> Console.ReadLine() ;<BR><BR> Console.WriteLine("{0}
    ",cpaAverage[a]); <BR><BR>So, only the line immediately following the for(...) statement is included in the loop, and of course by the time the loop has ended the value of a is what... that&#039;s it - 12!<BR><BR>You would have picked that up easily had you kept the scope of a to the loop itself. Try rewriting like so:<BR><BR> for(int a = 0; a &#060; 12; a++) <BR> { <BR> cpaAverage[a]=(cpa[a][0]+cpa[a][1]+cpa[a][2]+cpa[a][3]); <BR> <BR> Console.WriteLine("Value of a is {0}", a) ;<BR> Console.WriteLine("{0}
    ",cpaAverage[a]); <BR> Console.WriteLine("--------------------------------"); <BR> }<BR> Console.ReadLine() ;

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts