未处理的长度异常

  • 本文关键字:异常 未处理 c#
  • 更新时间 :
  • 英文 :


我需要能够打印出用户输入的温度数组,然后打印出来未排序,然后从waterdepth在索引1的下三个值开始在数组w在索引5未排序,排序和反转与w数组复制该数组,但每次它运行我有两个问题:

  1. 长度异常,但我不明白为什么会发生
  2. 在异常之前,它打印出索引为0的原始数组,然后重新打印0和1,一遍又一遍,直到它完成了数组的长度,如果有意义的话。

这是我遇到的错误未处理的例外:系统。ArgumentException:长度

using System;
class MainClass 
{
static void Main () 
{
Console.Write("how many depths do you want to enter?: ");
int depths = Convert.ToInt32(Console.ReadLine());
int [] temperature = new int [depths];
int [] w = new int [depths+5];
InputValues(temperature);
// array w will reference the same array
// as the temperature array
w = temperature;
DisplayOutput(w, "waterDepth Arraynn");
Array.Copy(temperature, 1, w, 5, 4);
Console.WriteLine("Array w Not Sorted");

Array.Sort(w); 
DisplayOutput(w, "array w sorted nn");
Array.Reverse(w);
DisplayOutput(w, "array w reversed nn");
} // end Main
public static void InputValues(int [] temp)
{
string inValue;
for(int i = 0; i< temp.Length; i++)
{
Console.Write("enter Temperature {0}: ", i+1);
inValue = (Console.ReadLine());
temp[i] = Convert.ToInt32(inValue);
} // end for
} // end input
public static void DisplayOutput(int [] anArray,string msg)
{
foreach(double wVal in anArray)
{
if (wVal>0)
msg +=wVal + "n";
} // end foreach
} //end disp
}//end class

您可能认为wtemperature长,但事实并非如此。请看下面的评论

int [] temperature = new int [depths];
int [] w = new int [depths+5]; // <-- w is depths+5 long
InputValues(temperature);
w = temperature; // <-- w is just another reference to temperature, hence depths long
Array.Copy(temperature, 1, w, 5, 4); <-- This fails.

你不能给一个数组分配一个长度,然后让它指向别的东西,并期望它保持它的长度。

使w = temp将w的长度变回与temp相同的长度