作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
为什么在第二个 For 循环中出现 ArrayIndexOutOfBoundsException
?
public class Ass1Ques2 {
void rotate() {
int[] a = {3, 8, 9, 7, 6};
int r = 2;
int[] t1 = new int[(a.length - r) + 1];
int[] t2 = new int[r + 1];
for (int y = 0; y <= r; y++) {
t2[y] = a[y];
}
// This loop is giving error
for (int i = 0; i <= a.length - r; i++) {
t1[i] = a[i + r];
}
for (int f = 0; f <= t1.length; f++) {
System.out.println(t1[f] + " ");
}
for (int n = 0; n <= t2.length; n++) {
System.out.println(t2[n] + " ");
}
}
public static void main(String[] args) {
Ass1Ques2 r = new Ass1Ques2();
r.rotate();
}
}
我不知道如何修复这个错误,我想我已经给了 t2 正确的长度。
我想根据 r 在内部顺时针旋转数组。
最佳答案
您访问a[i+r]
,考虑循环的最后一次迭代。 i = a.length-r
因此 i+r = a.length-r + r = a.length
超出范围。
如果您想旋转数组,我建议使用模 (%) 运算符来计算索引的新位置。因此,在实践中,将旋转添加到所有索引并在数组的长度上取模以获得新位置。
关于java - 为什么在第二个 For 循环中给出 ArrayIndexOutOfBoundsException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50895971/
我是一名优秀的程序员,十分优秀!