作者:Coco李可儿 | 来源:互联网 | 2023-05-24 10:37
我有一个问题,使用插入方法和反向方法,我试图在构造函数中,因为我是新的,这是一个练习示例.对于插入构造函数我有:它应该在数组中的索引处插入一个元素
public boolean insert(int index, int element)
{
int i;
newArray = new int[Array.length + 1];
for(i = index; i > newArray.length - 1; i++)
{
newArray[i] = newArray[i + 1];
for(i = 0; i
而我的反向构造函数是:
public boolean reverse(int start, int end)
{
int temp;
for(int i = start; i <(start + end) / 2 ; i++)
{
temp = Array[i];
Array[i] = Array[end - i];
Array[end - i] = temp;
}
return true;
}
当我使用插入构造函数时,它将替换数字,而不是创建一个新的数组来容纳额外的元素,在输出关闭之前它会给我一个异常错误.相反,它不会给我正确的输出.例如:我有一个数组[1,2,3,4,5,6,7,8,9,10]
,我想要反转它输出的数字3-7 [1,2,6,5,4,3,7,8,9,10]
.我不知道代码有什么问题.编辑:我也试图不使用任何Arrays.util方法/ ArrayList等
1> roeygol..:
数组有一个Java反向方法:
ArrayUtils.reverse(int[] array) //Reverses the order of the given array.
还有补充:
ArrayUtils.add(int[] array, int element) //Copies the given array and adds the given element at the end of the new array.