我是C#的新手,由于某种原因,我被抛出了一个以0和0为界的子字符串的IndexOutOfRangeException。
我不认为这是我的作用域的问题,因为我已经测试过了,以确保在使用它的地方定义了所有东西。
我正在试着做一个非常简单的字谜生成器:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string[] d = { "Apple", "Bass", "Cat", "Dog", "Ear", "Flamingo", "Gear", "Hat", "Infidel", "Jackrabbit", "Kangaroo", "Lathargic", "Monkey", "Nude", "Ozzymandis", "Python", "Queen", "Rat", "Sarcastic", "Tungston", "Urine", "Virginia", "Wool", "Xylophone", "Yo-yo", "Zebra", " "};
string var;
int len = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var = textBox2.Text;
//textBox1.Text = d[2];
for (int y = 0; y <= var.Length; y++)
{
for (int x = 0; x <= d.Length; x++)
{
if (d[x].Substring(0, 0).ToUpper() == var.Substring(len, len).ToUpper())
{
textBox1.Text = textBox1.Text + "\n" + d[x];
len = len + 1;
}
}
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
}发布于 2013-09-18 11:39:51
从零开始的数组(或从零开始的索引字符串)的上界比长度小一。
for (int y = 0; y < var.Length; y++)
{
for (int x = 0; x < d.Length; x++)发布于 2013-09-18 11:46:35
您尝试在两个位置读取超过数组结尾的内容:
for (int y = 0; y <= var.Length; y++) // here (var is a string which is an array of char)
{
for (int x = 0; x <= d.Length; x++) // and here数组使用从零开始的索引。因此,最后一个元素位于索引位置Length-1。
当您尝试访问position Length处的元素时,会得到IndexOutOfRangeException。这个位置是超过end的一个元素。
不要让你的循环计数器超过长度-1:
for (int y = 0; y < var.Length; y++)
{
for (int x = 0; x < d.Length; x++)发布于 2013-09-18 11:42:28
在基于零的索引中,您不能在结束点上进行索引,因为这将超出范围。对于长度10,您必须从0到9进行迭代:
for (int y = 0; y < var.Length; y++)
{
for (int x = 0; x < d.Length; x++)
{
if (d[x].Substring(0, 0).ToUpper() == var.Substring(len, len).ToUpper())
{
textBox1.Text = textBox1.Text + "\n" + d[x];
len = len + 1;
}
}
}https://stackoverflow.com/questions/18863428
复制相似问题