获得异常:indexoutofrangeunhadledexception [英] getting exception : indexoutofrangeunhadledexception

查看:71
本文介绍了获得异常:indexoutofrangeunhadledexception的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using System;
using System.Collections;
using System.Linq;
using System.Text;

namespace Generalsortingcon
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] items = { 60,30,40,20,80};
            int temp=0;
            int n = items.Length;
            for (int i = 0; i <n mode="hold" />            {
                for (int j = i+1; j <n-i;>                {
                    if (items[j] > items[j+1])//  here getting exception
                    {
                        temp = items[j];
                        items[j] = items[j+1];
                        items[j] = temp;
                    }

                }
                Console.WriteLine("values:" + Convert.ToString(items[i]));
               
            }
            
           
            Console.ReadKey();
           
        }
    }
}

推荐答案

像这样修改你的逻辑
int[] items = { 60, 30, 40, 20, 80 };
int temp = 0;
int n = items.Length;
for (int i = 0; i < n; i++)
{
    for (int j = i ; j < n - i - 1; j++)
    {
        if (items[j] > items[j + 1])// here getting exception
        {
            temp = items[j];
            items[j] = items[j + 1];
            items[j+1] = temp;
        }

    }
    //Console.WriteLine("values:" + Convert.ToString(items[i]));

}

for (int i = 0; i < n; i++)
{
    Console.WriteLine("values:" + Convert.ToString(items[i]));
}





您获得例外的原因是您试图将商品[4]与商品进行比较[5]哪个不存在....

因此你需要将你的终止条件限制在nI-1



你也需要更改j的初始值...



The reason you are getting exception is you are trying to compare items[4] with items[5] which doesnot exists....
so you need to restrict you termination condition to n-I-1

and also you need to change the initial value of j ...


这篇关于获得异常:indexoutofrangeunhadledexception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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