如何解决C#中的索引超出范围 [英] How to solve index out of range in C#

查看:348
本文介绍了如何解决C#中的索引超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的,我编写了以下代码片段,用一条染色体填充大小为25的种群,其中每条染色体是一个大小为5 * 5的矩阵,其中此矩阵中的每个元素将为0或1.此代码创建遗传算法的初始种群:



Dear all, I wrote the following code snippet to fill a population of size 25 with a chromosomes where each chromosome is a matrix of size 5*5 where each element in this matrix will be either 0 or 1. This code to create the initial population for a genetic algorithm :

using System;
using System.IO;
using System.Text;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
using AUV_Topology;
using System.Collections.Generic;
using System.Media;

namespace AUVtopology
{
    public partial class Form1 : Form
    {


static int[,] auvChromosomes;

static int[][,] population;

private void moveGenetic_Click(object sender, EventArgs e)
        {

            FileStream fs = new FileStream("C:/Users/Welcome/Desktop/intialPopulation.txt", FileMode.Append, FileAccess.Write);

            population = new int[25][,]; // jagged array

            Random rnd = new Random(); // to gereate random number (either 0 or 1)

            calculateCellsCenters(200, 325); // Compute all the center points (Xc,Yc) for all cells of the partitioned region (grid) 

            auvChromosomes = new int[5, 5];

            for (int i = 0; i < population.Length; i++)
            {

                population[i] = new int[5, 5];

            }

          using (StreamWriter sw = new StreamWriter(fs))

            {

                for (int i = 0; i < population.Length; i++)
                {

                    for (int j = 0; j < population[i].Length; j++)
                    {

                        for (int k = 0; k < auvChromosomes.Length; k++)
                        {


                            auvChromosomes[j, k] = rnd.Next(0, 2);

                            sw.Write("|" + auvChromosomes[j, k] + "|");


                        } // end-inner-for

                        sw.WriteLine();

                    } // end-outer-inner-for

                    sw.WriteLine("----------------------------------------------------------------------");

                } // end-outer-for

           


            } // end-using



            //Genetic_Algorithm(population);



        }

}// end-main-class

}// end-name-space







我不知道这个空例外在哪里或超出范围索引? ?我在代码中没有看到这一点我认为这是真的!



为什么我点击按钮时出现以下错误:






I do not know where is this null exception or out of range index ?? I do not see this in my code I think it is true !!

Why I got the following error when I clicked the button :

See the end of this message for details on invoking 
just-in-time (JIT) debugging instead of this dialog box.

************** Exception Text **************
System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at AUVtopology.Form1.moveGenetic_Click(Object sender, EventArgs e) in C:\Users\Welcome\Desktop\project\GAAPS\AUV_Topology\Form1.cs:line 825
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)


************** Loaded Assemblies **************
mscorlib
    Assembly Version: 4.0.0.0
    Win32 Version: 4.6.1648.0 built by: NETFXREL3STAGE
    CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll
----------------------------------------
AUV_Topology
    Assembly Version: 1.0.0.0
    Win32 Version: 1.0.0.0
    CodeBase: file:///C:/Users/Welcome/Desktop/project/GAAPS/AUV_Topology/bin/Release/AUV_Topology.exe
----------------------------------------
System.Windows.Forms
    Assembly Version: 4.0.0.0
    Win32 Version: 4.6.1586.0 built by: NETFXREL2
    CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System
    Assembly Version: 4.0.0.0
    Win32 Version: 4.6.1647.0 built by: NETFXREL3STAGE
    CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
System.Drawing
    Assembly Version: 4.0.0.0
    Win32 Version: 4.6.1586.0 built by: NETFXREL2
    CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
Accessibility
    Assembly Version: 4.0.0.0
    Win32 Version: 4.6.1586.0 built by: NETFXREL2
    CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/Accessibility/v4.0_4.0.0.0__b03f5f7f11d50a3a/Accessibility.dll
----------------------------------------
Microsoft.VisualBasic.PowerPacks.Vs
    Assembly Version: 10.0.0.0
    Win32 Version: 10.0.30319.1
    CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/Microsoft.VisualBasic.PowerPacks.Vs/10.0.0.0__b03f5f7f11d50a3a/Microsoft.VisualBasic.PowerPacks.Vs.dll
----------------------------------------
Microsoft.VisualBasic
    Assembly Version: 10.0.0.0
    Win32 Version: 14.6.1586.0 built by: NETFXREL2
    CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/Microsoft.VisualBasic/v4.0_10.0.0.0__b03f5f7f11d50a3a/Microsoft.VisualBasic.dll
----------------------------------------

************** JIT Debugging **************
To enable just-in-time (JIT) debugging, the .config file for this
application or computer (machine.config) must have the
jitDebugging value set in the system.windows.forms section.
The application must also be compiled with debugging
enabled.

For example:

<configuration>
    <system.windows.forms jitDebugging="true" />
</configuration>

When JIT debugging is enabled, any unhandled exception
will be sent to the JIT debugger registered on the computer
rather than be handled by this dialog box.





注意:第825行是在此声明中:





Note : Line 825 is at this statement :

FileStream fs = new FileStream("C:/Users/Welcome/Desktop/intialPopulation.txt", FileMode.Append, FileAccess.Write);





但是当我清理解决方案时,重建项目,并运行调试器..它已指向以下声明:





But when I clean the solution, rebuild the project, and run the debugger .. it has pointed to the following statement :

auvChromosomes[j, k] = rnd.Next(0, 2);





我尝试过:



我需要正确打印初始种群,其中每个染色体是一个大小为5 * 5的矩阵...



What I have tried:

I need to print the initial population correctly where each chromosome is a matrix of size 5 * 5 ...

推荐答案

for (int k = 0; k < auvChromosomes.Length; k++)



长度( auvChromosomes.Length )是数组的总长度,即5 x 5 ,即25,但每个索引只从0到4.也是每次填充 auvChromosomes 而不是种群中的每个元素 array。


The length (auvChromosomes.Length) is the total length of the array, which is 5 x 5, i.e 25, but each index only runs from 0 to 4. Also you are populating auvChromosomes each time rather than each element in your population array.


错误非常明确:我认为它不在你想象的那一行。在VS中,CTRL + G会让你直接进入该行,但更好的方法是在调试器中运行你的代码,看看究竟发生了什么。

猜测,如果是行825正确的文件,然后你有编译错误阻止你运行最新代码,因此错误行号与你正在查看的代码不匹配。



干净后重建解决方案,并确保没有错误,然后在调试器中运行它。当错误发生时,它将抛出异常并且代码将停止 - 然后您可以使用调试器来检查变量并确切地查看哪个索引超出了什么数组的范围。



但没有它,我们无法帮助!
The error is pretty explicit: I don't think it's on the line you think it is. In VS, CTRL+G will let you directly to the line, but a better way is to run your code in the debugger and see exactly what is going on.
At a guess, if that is line 825 of the right file, then you have compilation errors which have prevented you running the "latest" code, and as a result the error line number doesn't match the code you are looking at.

Rebuild your solution after a clean, and make sure there are no errors, then run it in the debugger. When the error occurs it will throw an exception and you code will stop - you can then use the debugger to examine variables and look at exactly what index is out of range of what array.

But without that, we can't help!


参见 Array.Length Property(System) [ ^ ]:

See Array.Length Property (System)[^]:
Quote:

获取数组所有维度中元素的总数。

Gets the total number of elements in all the dimensions of the Array.

所以你在计算 j k 最多25个。



使用 GetUpperBound()代替相应的维度或常量值5.

So you are counting j and k up to 25.

Use GetUpperBound() for the appropriate dimension or the constant value 5 instead.


这篇关于如何解决C#中的索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆