java - for循环中数组元素的减法(java.lang.ArrayIndexOutOfBoundsException)
问题描述
我需要减去:
(2 - 0) 和 (4 - 2)。
我需要这个来找出丢失了多少数字。我只是第一次学习编码,从逻辑上讲,这对我来说似乎是正确的。
只要“n”小于“4”的“(statues[statues.length-1])”,代码减法,所以它应该停在“2”。所以我不明白为什么我会收到这个错误:
java.lang.ArrayIndexOutOfBoundsException:索引 3 超出长度 3 的范围
事实上,如果我打印“c”,我可以看到正确的结果,但显然它会继续计算,因为错误行是“c”行。
我已经将代码更改为不同的版本并且它可以工作,但是根据数组中的数字,出了点问题。
公共类 MakeArrayConsecutive2 {
public static void main(String[] args) {
int[] statues = {0, 2, 4};
makeArrayConsecutive2(statues);
}
public static int makeArrayConsecutive2(int[] statues) {
Arrays.sort(statues);
int count = 0;
for (int n = statues[0]; n < statues[statues.length-1]; n++) {
int c = statues[n + 1] - statues[n];
System.out.println(c);
if (c != 1) {
count += c - 1;
}
}
System.out.println(count);
return 0;
}
}
解决方案
似乎这里的主要误解是关于如何在 for 循环中迭代某些结构。在这里,你写了
for (int n = statues[0]; n < statues[statues.length-1]; n++) {
int c = statues[n + 1] - statues[n];
}
这是不正确的,因为当您尝试使用雕像[statues[2]] 时,您实际上是在使用不存在的雕像[4];您可能只想参考雕像[n]。对此的解决方案是将 n 视为一个常规整数,它采用 range 中的所有值[0, statues.length - 1)
。这看起来更像
for (int n = 0; n < statues.length - 1; n++) {
int c = statues[n + 1] - statues[n];
}
我希望这会有所帮助,如果我错误地解释了您的意图,请告诉我。
推荐阅读
- c# - API不接受对象列表作为参数.Net Core webAPI
- python-3.x - 跨熊猫行的参考总和 df
- javascript - 如何强制 EXTJS 中的数据视图项保持相等的垂直空间?
- c++ - 为`std::variant`重载&&会破坏不相关的`std::map`
- excel - VBA如何复制所有行直到空白行
- nginx - 502 Bad Gateway with Kubernetes Ingress Digital Ocean
- database - AWS:仅允许从 VPC 访问 Lambda
- terminal - Git Bash 终端在最小化时保持关闭
- php - Cloudways PHP FPM 设置——分号?
- c# - 从 InputBase 继承的自定义输入中的 Blazor 级联参数问题