gpt4 book ai didi

java - 尝试在 Java 中的数组中创建 AddBefore 方法。不使用ArrayList

转载 作者:太空宇宙 更新时间:2023-11-04 11:48:18 25 4
gpt4 key购买 nike

public class Arrays {

private static int[] vals = {1,3,2,5};

public void addBefore(int input, int before){
int[] temp = new int[vals.length*2];
//int[] temp2 = new int [vals.length * 2];
int position = 0;
boolean check = false;
for(int i = 0; i<vals.length; i++){
check = false;

if(vals[i] == (before)){
check = true;
temp[i] = input;
position = i;
break;
}
temp[i] = vals[i];
}

vals[position] = input;
int previous = input;
int current = 0;
for(int i=position;i<vals.length;i++){
current = vals[i];
vals[i] = previous;
previous = current;
}
}

public static void main(String[] args){
Arrays a = new Arrays();

a.addBefore(1, 2);
for(int i = 0; i<vals.length; i++){
System.out.println(vals[i]);
}
}
}

所以我尝试在 Java 中创建一个 addBefore 方法。它有两个参数 input 和 before。我们必须将输入推到给定值之前,而不替换任何内容。当我运行这段代码后。打印出来的数组是{1,3,1,1}。我需要它停止取代并只是插入它前进。

最佳答案

您是否正在寻找这样的东西:

public static int[] addBefore(int[] array, int input, int before)
{
//create a new array with 1 more space
int[] newArray = new int[array.length + 1];

//copy in the original array up to the insertion point
for (int x = 0; x < before; x++)
{
newArray[x] = array[x];
}

//element at index 'before' will be pushed one forward; 'before' is now the new one
newArray[before] = input;

//fill in the rest
for (int x = before + 1; x < newArray.length; x++)
{
//need to offset it by one to account for the added int
newArray[x] = array[x - 1];
}

return newArray;
}


public static void main(String[] args)
{
int[] vals = {1,3,2,5};

for(int i = 0; i<vals.length; i++){
System.out.print(vals[i] + ",");
}
System.out.println();

vals = addBefore(vals, 1, 2);

for(int i = 0; i<vals.length; i++){
System.out.print(vals[i] + ",");
}
}

关于java - 尝试在 Java 中的数组中创建 AddBefore 方法。不使用ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42103710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com