C# 序列未处理的异常
C# sequence unhandled exception
//1. add 10 numbers in sequence , print only steam numbers.
int[] seq= new int[10];
int n = 0;
int[] seq2= new int[n];
for (int i = 0; i < seq.Length; i++)
{
Console.WriteLine("Add number ");
seq[i] = int.Parse(Console.ReadLine());
if (seq[i]%2==0)
{
seq2[n] = seq[i];
n++;
}
}
for (int i = 0; i < seq2.Length; i++)
{
Console.WriteLine(seq2[i]);
}
sequence2 有问题,程序没有说明任何问题,有人可以帮忙吗?这与我以其他方式完成的任务无关,但我只是想了解我在这里做错了什么。
您在下面显示的代码部分中声明了长度为 0
的 Seq2
数组。因此,当您执行此 Index was outside the bounds of the array 异常时,它总是会失败 seq2[n] = seq[i];
.
int n = 0;
int[] seq2= new int[n];
改为将 Seq2
声明为列表。像这样..
var seq2= new List<int>();
然后这样做..
seq2.Add(seq[i]);
您的最终代码将如下所示..
int[] seq= new int[10];
var seq2= new List<int>();
for (int i = 0; i < seq.Length; i++)
{
Console.WriteLine("Add number ");
seq[i] = int.Parse(Console.ReadLine());
if (seq[i]%2==0)
{
seq2.Add(seq[i]);
}
}
for (int i = 0; i < seq2.Count(); i++)
{
Console.WriteLine(seq2[i]);
}
因为你不知道第二个数组中元素的数量,而且 C# 没有动态数组(我认为),所以只用列表代替:
int[] seq= new int[10];
int n = 0;
List<int> seq2= new List<int>;
for (int i = 0; i < seq.Length; i++)
{
Console.WriteLine("Add number ");
seq[i] = int.Parse(Console.ReadLine());
if (seq[i]%2==0)
{
seq2.Add(seq[i]);
n++;
}
}
for (int i = 0; i < seq2.Length - 1; i++)
{
Console.WriteLine(seq2[i]);
}
数组是必须的吗?
int n = 10;
for (int i = 0; i < n; i++)
{
Console.WriteLine("Add number ");
int a = int.Parse(Console.ReadLine());
if (a%2==0)
{
Console.WriteLine(a);
}
}
如果是,您将需要一个列表,因为您不知道其中有多少是偶数。
编辑:只读底线..
//1. add 10 numbers in sequence , print only steam numbers.
int[] seq= new int[10];
int n = 0;
int[] seq2= new int[n];
for (int i = 0; i < seq.Length; i++)
{
Console.WriteLine("Add number ");
seq[i] = int.Parse(Console.ReadLine());
if (seq[i]%2==0)
{
seq2[n] = seq[i];
n++;
}
}
for (int i = 0; i < seq2.Length; i++)
{
Console.WriteLine(seq2[i]);
}
sequence2 有问题,程序没有说明任何问题,有人可以帮忙吗?这与我以其他方式完成的任务无关,但我只是想了解我在这里做错了什么。
您在下面显示的代码部分中声明了长度为 0
的 Seq2
数组。因此,当您执行此 Index was outside the bounds of the array 异常时,它总是会失败 seq2[n] = seq[i];
.
int n = 0;
int[] seq2= new int[n];
改为将 Seq2
声明为列表。像这样..
var seq2= new List<int>();
然后这样做..
seq2.Add(seq[i]);
您的最终代码将如下所示..
int[] seq= new int[10];
var seq2= new List<int>();
for (int i = 0; i < seq.Length; i++)
{
Console.WriteLine("Add number ");
seq[i] = int.Parse(Console.ReadLine());
if (seq[i]%2==0)
{
seq2.Add(seq[i]);
}
}
for (int i = 0; i < seq2.Count(); i++)
{
Console.WriteLine(seq2[i]);
}
因为你不知道第二个数组中元素的数量,而且 C# 没有动态数组(我认为),所以只用列表代替:
int[] seq= new int[10];
int n = 0;
List<int> seq2= new List<int>;
for (int i = 0; i < seq.Length; i++)
{
Console.WriteLine("Add number ");
seq[i] = int.Parse(Console.ReadLine());
if (seq[i]%2==0)
{
seq2.Add(seq[i]);
n++;
}
}
for (int i = 0; i < seq2.Length - 1; i++)
{
Console.WriteLine(seq2[i]);
}
数组是必须的吗?
int n = 10;
for (int i = 0; i < n; i++)
{
Console.WriteLine("Add number ");
int a = int.Parse(Console.ReadLine());
if (a%2==0)
{
Console.WriteLine(a);
}
}
如果是,您将需要一个列表,因为您不知道其中有多少是偶数。
编辑:只读底线..