在数组中的任何位置插入元素
我对编程的新手相对较新,对一些帮助将不胜感激。我正在收到错误消息:数组索引从界限出来。
static int[] insert1(int z, int arr[], int ins, int p)
{
int i;
int newarray[] = new int [z + 1];
for (i = 0; i < z + 1 ; i++) {
if (i < p - 1 )
newarray[i] = arr[i];
else if (i == p - 1)
newarray[i] = ins;
else
newarray[i] = arr[i - 1];
}
return newarray;
}
public static void main(String[] args) {
int ins = 20;
int z = 5;
Scanner scan = new Scanner(System.in);
int p = Integer.parseInt((scan.next()));
arr = insert1(a, arr, ins, p);
System.out.println("Insert Array:\t" + Arrays.toString(arr));
}
}
I'm relatively new to programming and some help would be appreciated. I'm receiving the error message: array index out of bounds.
static int[] insert1(int z, int arr[], int ins, int p)
{
int i;
int newarray[] = new int [z + 1];
for (i = 0; i < z + 1 ; i++) {
if (i < p - 1 )
newarray[i] = arr[i];
else if (i == p - 1)
newarray[i] = ins;
else
newarray[i] = arr[i - 1];
}
return newarray;
}
public static void main(String[] args) {
int ins = 20;
int z = 5;
Scanner scan = new Scanner(System.in);
int p = Integer.parseInt((scan.next()));
arr = insert1(a, arr, ins, p);
System.out.println("Insert Array:\t" + Arrays.toString(arr));
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于初学者来说,不必将长度作为输入,这将使您的生活变得更加轻松。只需使用 arr.length 就会得到相同的结果,而不必担心另一个变量。
您的插入有一个良好的开始。一种更有效、更简单的方法是使用多个 for 循环。
如果这不能满足您的要求,请告诉我,我可以对其进行修改。
PS 如果您愿意更改更多代码,您应该考虑使用 列表 代替。我很乐意在我的答案中添加一个带有列表的版本。
For starters, it will make your life a lot easier to not have to put the length in as an input. Just using arr.length will give you the same result without having to worry about another variable.
You have a good start for an insertion. A more efficient and less complex way to do it would be with multiple for-loop.
Let me know if this doesn't do what you're looking for and I can modify it.
P.S. If you are comfortable with changing more of your code you should look into using Lists instead. I'd be happy to add a version with a list to my answer.
我将使用此方法来将操作插入数组中,以通过将元素向右移动到所需位置的右侧来执行的任何位置,例如:
{1,2,2,3,3,4,5 ,6、7、8、9 10}
,我们要插入x
作为所需位置的元素x = 50;
特定
pos = 5 ;
I will do with this method to insert operation in an array at any position I had performed by shifting elements to the right , which are on the right side of required position for instance :
{1 , 2 , 3 , 4 ,5 ,6 ,7 ,8 ,9 10}
and we want to insertx
as element at required positionx = 50;
specific
pos = 5;