我的任务是创建一个与拼接具有相同功能的方法,但是我无法将适当的值存入适当的索引。我的代码工作如下,如何在Java中编写类似拼接的方法
public void PlaceElementAt(int newValue, int index) throws ArrayIndexOutOfBoundsException {
//check that index is valid
if (index >= 0 && index <= data.length) { //Checks that the index is within position 0 and 7 by default.
System.out.println ("Index is valid"); //returns index is valid if so
}
//increase size if necessary
if (data.length == numElements) { //checking if the number of elements is filling the spaces
doubleCapacity(); // calls upon the double capacity method if it is
}
if (numElements==0) {
data[numElements] = newValue;
System.out.println ("Element: " + data[numElements] + " at index: " + index);
numElements++;
}
//shuffle values down from index
else {
int bottompos = numElements-1;
int loopcount = numElements-index;
int NewBottom = numElements+1;
for (int i=0; i<loopcount; i++){
data[bottompos]=data[NewBottom];
bottompos--;
NewBottom--;
}
//insert newValue at index
data[numElements] = newValue;
System.out.println ("Element: " + data[numElements] +" at index: " + index);
numElements++;
}
}
我后来在我的主要方法中给出的命令时,我的问题很明显。
myData.PlaceElementAt(3,0)
myData.PlaceElementAt(2,5)
myData.PlaceElementAt(7,3)
一次检查我的断点,我看到的值被添加到数组中,但是它们是从索引0开始逐个添加的。任何建议都会大大有所帮助。
Java没有一个拼接的方法。 – shmosel
@shmosel我认为他正在努力创造一个。至少,这是我从他的问题描述中收集到的。 –
@HypnicJerk请参阅[修订历史记录](http://stackoverflow.com/posts/42496438/revisions)了解我的评论。 – shmosel