索引越界-C#
好吧,我自己也试过一遍代码,但是IDE-Visual Studio总是说这是错误的 索引超出了界限错误索引越界-C#,c#,.net,arrays,indexing,C#,.net,Arrays,Indexing,好吧,我自己也试过一遍代码,但是IDE-Visual Studio总是说这是错误的 索引超出了界限错误 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//declare Arrays for buttons and
//LEDs
int[] buttonArray = new int[4]; // Left to right .-.. ------
//left, top, bottom, right
int[,] ledArray = new int[10, 10];
//declare variables
int strandSnake = 0;
int requestR = 0;
int countDeclareButtonArray = 0;
int countWriteButtonArray = 0;
//code
if (strandSnake != 1)
{
}
//Declaring the four buttons
for (int ip = 0; ip < 4; ip++)
{
buttonArray[countDeclareButtonArray] = countDeclareButtonArray;
countDeclareButtonArray++;
}
// writing the four buttons to the screen.
foreach (int ip in buttonArray)
{
requestR = buttonArray[countWriteButtonArray];
countWriteButtonArray++;
}
Console.ReadLine();
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
命名空间控制台应用程序1
{
班级计划
{
静态void Main(字符串[]参数)
{
//为按钮和按钮声明数组
//发光二极管
int[]buttonArray=new int[4];//从左到右。------------
//左、上、下、右
int[,]ledArray=新的int[10,10];
//声明变量
int-strandSnake=0;
int-requestR=0;
int countDeclareButtonArray=0;
int countWriteButtonArray=0;
//代码
如果(strandSnake!=1)
{
}
//声明四个按钮
对于(int ip=0;ip<4;ip++)
{
buttonArray[countDeclareButtonArray]=countDeclareButtonArray;
countDeclareButtonArray++;
}
//将四个按钮写入屏幕。
foreach(按钮数组中的int ip)
{
requestR=buttonArray[countWriteButtonArray];
countWriteButtonArray++;
}
Console.ReadLine();
}
}
}
您应该从0中知道C#中数组的索引范围。。数组长度-1
所以,如果你有
int[] a = new int[4];
您可以访问a[0]。a[1]、a[2]、a[3]
但是当您访问a[4]时,您将得到索引超出了界限的错误
调试它并搜索错误从何处来查看代码段,
countWriteButtonArray
变量的值是4
,因此您必须将0
分配给countWriteButtonArray
countWriteButtonArray=0;
foreach (int ip in buttonArray)
{
requestR = buttonArray[countWriteButtonArray];
countWriteButtonArray++;
}
如果要从按钮数组
获取元素,可以使用:
foreach (int ip in buttonArray)
{
//
}
使用for循环使用索引迭代数组
for(countWriteButtonArray=0;countWriteButtonArray<=buttonArray.GetUpperBound(0);countWriteButtonArray++)
{
requestR = buttonArray[countWriteButtonArray];
}
对于(countWriteButtonArray=0;countWriteButtonArray=0),请格式化您的代码并提供更多信息。哪一行产生错误?能否将整个消息粘贴到此处?