Java 是否删除项目并将其添加到阵列?
我正在尝试编写一个接收数字数组的方法。如果数组中有任何零,它将添加另一个零,但数组必须保持相同的长度,以便从新数组中删除最后一个数字。这是我已经开始做的,但我认为它不会有任何进展Java 是否删除项目并将其添加到阵列?,java,arrays,Java,Arrays,我正在尝试编写一个接收数字数组的方法。如果数组中有任何零,它将添加另一个零,但数组必须保持相同的长度,以便从新数组中删除最后一个数字。这是我已经开始做的,但我认为它不会有任何进展 public static int[] MoveToRightOne(int userArray[] ) { int newArray [] = new int[userArray.length + 1]; int zero = 0; for(int i = 0; i < user
public static int[] MoveToRightOne(int userArray[] )
{
int newArray [] = new int[userArray.length + 1];
int zero = 0;
for(int i = 0; i < userArray.length; i++)
{
if (userArray[i] == 0)
zero = zero + 1;
newArray[i + zero] = userArray[i - 1];
}
return(userArray);
}
我想这会满足你的要求
public static int[] MoveToRightOne(int userArray[] ) {
// the new array will have the same length as the input
int newArray [] = new int[userArray.length];
// two indexes i for the input and j for the output
int i = 0, j = 0;
while(j < userArray.length){ // while it's not the end of the output
// we insert the element
newArray[j] = userArray[i];
if(userArray[i] == 0){ // if the current element is a 0
// we insert an additional 0
j ++;
if(j < userArray.length)
newArray[j] = 0;
}
// increment indexes
i ++;
j ++;
}
return newArray;
}
以下代码将用于您的目的
public static int[] MoveToRightOne(int userArray[] ) {
int newArray [] = new int[userArray.length];
for(int i = 0, j = 0;j < userArray.length;i++,j++){
newArray[j] = userArray[i];
if(userArray[i] == 0 && j+1 < userArray.length){
j ++;
newArray[j] = 0;
}
}
return(newArray);
}
建议:告诉我们你在用什么语言?评论!请添加注释,描述代码的每个部分打算做什么。我不太理解该方法的目标。如果有任何零,它只是用零替换数组的最后一个元素吗?还是数组中的每一个零都会添加一个零?如果是,那么它们将添加到数组的哪个索引?相关:它在数组中的每个零实例之后添加一个零。因此,为了保持数组的原始长度,它从末尾删除整数。下面是一个输入和输出示例:1 2 0 3 0 4 0 5 0 6 0 0 1 2 0 0 3 0 0 4 0 0 5 0 0如果userArray[i]==0和j==userArray.length-1,这将不起作用;它将增加它,并尝试在newArray[userArray.length]处插入,这超出了界限!