c# - 将项目添加到数组时,索引超出了数组的范围
问题描述
这是我的代码
public static int[] MoveZeroes(int[] arr)
{
// TODO: Program me
int zeroCount = 0;
int[] temp = { };
int numberItems = 0;
foreach (var a in arr)
{
if (a == 0)
{
zeroCount += 1;
}
else
{
temp[numberItems] = a;
}
numberItems += 1;
}
return new int[] { };
}
我用它喜欢
int[] f = MoveZeroes(new int[] {1, 2, 1, 1, 3, 1, 0, 0, 0, 0});
但这给了我Index was outside the bounds of the array
在线错误
temp[numberItems] = a;
如何在数组中添加项目?我究竟做错了什么 ?
解决方案
int[] temp = { }
这将创建一个长度为 0 个元素的整数数组。您无法插入其中,因为它的长度为 0。
使用 a List<int>
,您可以动态添加到它:
public static int[] MoveZeroes(int[] arr)
{
// TODO: Program me
int zeroCount = 0;
var temp = new List<int>();
int numberItems = 0;
foreach (var a in arr)
{
if (a == 0)
{
zeroCount += 1;
}
else
{
temp.Add(a);
}
numberItems += 1;
}
return temp.ToArray();
}
推荐阅读
- javascript - 未捕获的 TypeError:t 未定义,同时尝试通过 ThreeJS ObjectLoader 加载 json
- postgresql - postgresql 存储跨越午夜的开放时间
- javascript - 寻找一种更好的方法来映射对象数组并返回 id 匹配的特定键
- javascript - 阻止键盘从按钮按下弹出
- r - 如何根据三列删除重复项,但我使用 R 保留特定列中编号最高的行?
- java - 在Activity中保存ArrayList
- kubernetes-ingress - 访问在 Kubernetes 集群上使用 PingIdentity devops 部署的 Pingfederate 控制台时出现内部服务器错误
- flutter - 未选择 DropDownButton 项目
- node.js - 如何使用 Nodejs 将通行证保存到 Google Pay?
- amazon-cognito - Cognito 多租户用户池