2014-10-28 125 views
0

我正在尝试编写一个接收数字数组的方法。如果数组中有任何零,它将添加另一个零,但数组必须保持相同的长度,以便从新数组中删除最后一个数字。这是我已经开始做的事情,但我不认为这是在任何地方。删除和添加项目到数组?

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); 
} 
+1

建议什么:告诉我们您正在使用的是什么语言? – 2014-10-28 02:02:50

+0

评论!请添加注释,说明您的代码*的每个部分*打算做什么。 – 2014-10-28 02:08:16

+0

我正在使用Java。 – Bill 2014-10-28 02:09:15

回答

0

我认为这会做你想要

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; 
} 
0

下面的代码将成为你的目的

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); 
} 
+0

this won如果'userArray [i] == 0'和'j == userArray.length - 1'不工作,它会增加它,并尝试插入'newArray [userArray.length]'这是超出界限! – webNeat 2014-10-28 02:32:55

+0

@webNeat谢谢。 – 2014-10-28 02:37:12