抛出索引超出范围异常

本文关键字:异常 范围 索引 | 更新日期: 2023-09-27 18:31:38

我对 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)
        {
        }
    }
}

抛出索引超出范围异常

您正在尝试在两个位置读取数组的末尾:

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]。

当您尝试访问位置 [Length] 处的元素时,您将获得 IndexOutOfRangeException。这个位置是过了最后的一个元素。

不要让循环计数器超过 Length-1:

for (int y = 0; y < var.Length; y++)  
{                 
    for (int x = 0; x < d.Length; x++)

从零开始的数组(或从零开始的索引字符串)的上限是长度少一。

for (int y = 0; y < var.Length; y++)
{
    for (int x = 0; x < d.Length; x++)

在从开始的索引中,不能在端点上编制索引,因为这会超出范围。对于长度 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;
        }
    }
}