你需要确保你的支持数组a
有足够的空间,让您可以插入一个新元素。
int[] a= new int[]{1,2,3,5}; // this has only 4 elements, you can't add a 5th
所以,你可以这样做:
public void adding(){
// ask user for input.... and all that
// you need an array with one more element than a. lets call it b
int[] b = new int[a.length + 1];
// now you need to search for x. (this is, if x is a number in your array and not an index..it wasn't clear to me)
// so if x is a number in the array (and not the index) you need to get the index of that number:
int index = 0;
for (; index < a.length; index++) { // your index variable will increment on each step
if (a[index] == x) {
break; // and you break out of the loop once you found x
}
}
// now you know the index of x
// first make a copy of the partial array after x (in your example its just {5})
int[] c = Arrays.copyOfRange(a, index, a.length); // this will copy all elements of a from "index" to "length"
// and here the loop that will actually insert the new number and move the rest:
int cIndex=0; // we need that counter later to loop through the new array c
for (int i = 0; i < b.length; i++) { // loop through every element of b
if (i <= index) { // if i is currently smaller than your wanted index (there where you will find x)
b[i] = a[i]; // then just copy the contents of a
} else if (i == index+1) { // we just stepped over x
b[i] = d; // so you can add your new number here
} else {
b[i] = c[cIndex]; // and here you copy the rest into b (the partial array we called c earlier)
cIndex++; // we need that new index, to get always the next element
}
}
就是这样。看起来很复杂,而且迄今还不是最好或最有效的解决方案。但它的工作原理,我希望它可以帮助你更进一步!
它可能只是我,但我不认为使用错误的数据结构编写代码是一个很好的教学示例。对于这个问题,Java总是有大量的集合,比原始数组做得更好。 – 2014-12-07 20:33:51
@MattCoubrough:true,数组是最不实用的数据结构,在中间的某处插入元素不再与堆栈有任何关系。当然,我写的东西缺乏教育价值。我只是想在这种情况下给出一个关于如何处理数组的简单例子。现在它由OP来优化程序并切换到列表或者更适合于那种问题。但是在跳转到列表之前从数组开始并不完全理解后台发生的事情仍然很好。 – GameDroids 2014-12-07 20:48:23
也许你可以改进答案,也展示如何正确地做到这一点,或为什么阵列不适合这项工作? – 2014-12-07 20:55:30