2014-10-28 119 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

相關問題