需要帮助解决 Java 数组问题
我需要一点帮助。我正在尝试编写一个小型 Java 程序,该程序创建并返回一个包含 a 的所有元素的数组,其中每个元素都是重复的。但是,每次我尝试执行代码时,都会出现“越界”异常。请告诉我我哪里出错了。谢谢!这是我到目前为止所拥有的:
public class integerStutter
{
public static int[] stutter(int [] a){
int[] j = new int[a.length*2];
for(int i=0; i < j.length; i++){
j[i] = a[i];
j[i+1] = a[i];
i++;
}
return j;
}
}
I need a little help. I'm trying to put together a small Java program that creates and returns an array containing all elements of a, each of these duplicated. However, every time I try to execute my code I get an "out of bounds" exception. Please give me an idea of where I'm going wrong. Thanks! Here is what I have so far:
public class integerStutter
{
public static int[] stutter(int [] a){
int[] j = new int[a.length*2];
for(int i=0; i < j.length; i++){
j[i] = a[i];
j[i+1] = a[i];
i++;
}
return j;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
新旧数组的大小不相等。您尝试使用新数组(双倍大小)的有效索引来访问旧数组中的元素,这导致了异常。
相反尝试:
The old and new array are not of equal sizes. You are trying to access elements from old array using valid indices for the new array (which is of double size) and this is causing the exception.
Instead try:
因此,数组
j
、a
的大小不相等。但循环运行直到j.length
-So, the size of arrays
j
,a
are not equal. But the loop runs untilj.length
-你可以这样做
you can do it like this
如果我正确理解了这个问题,这将满足您的需要。这也是一个很好的清洁解决方案。
If I understand the question correctly, this will do what you need. It is also a nice clean solution.