2017-03-19 76 views
-3

我必須創建一個數組,該數組需要兩個整數並且創建一個具有相同內容的新數組,但值1的出現被替換爲兩個。有人可以幫助我,這是我迄今爲止。 assertArrayEquals部分存在錯誤。通過替換整數創建數組

public static replace(int[] in, int find, int replace) { 
     for (int i = 0; i < in.length; i++) { 
      if (in[i] == find) { 
       in[i] = replace; 
       return; 
      } 
     } 
    } 



assertArrayEquals(new int[]{5, 5, 5, 5}, Array.replace(new int[]{5, 0, 0, 5}, 0, 5)); 
+2

什麼是你的問題? –

+1

您能否提供更多詳情?給出一些示例輸入,你期望輸出什麼? –

+0

我無法生成新的數組,其中值1的出現值被替換爲值2 –

回答

1
public static void replace(int[] in, int find, int replace) { 
    for (int i = 0; i < in.length; i++) { 
     if (in[i] == find) { 
      in[i] = replace; 
//    do not return; continue to replace other elems 
     } 
    } 
} 

要進行測試,使用此:

int[] a =new int[]{5, 0, 0, 5}; 
Array.replace(a, 0, 5); 
assertArrayEquals(new int[]{5, 5, 5, 5}, a); 

可能可以使用的功能:

public int[] void replace(int[] in, int find, int replace) { 
    for (int i = 0; i < in.length; i++) { 
     if (in[i] == find) { 
      in[i] = replace; 
//    do not return; continue to replace other elems 
     } 
    } 
    return in; 
} 

而現在這應該工作:

assertArrayEquals(new int[]{5, 5, 5, 5}, Array.replace(new int[]{5, 0, 0, 5}, 0, 5)); 
+0

我如何繼續替換元素? –

+0

請勿使用「return;」。你留在循環中。 – laune

0

嘗試刪除return聲明

for (int i = 0; i < in.length; i++) { 
     if (in[i] == find) { 
      in[i] = replace; 
     } 
} 
0

您正在從這個函數太早返回:

for each value 'x' in the input array: 
    if 'x' is equal to our 'find' value, replace it and return 

這裏的問題是,一旦你找到一個匹配值,則在更換(好) ,但是你回來了(壞)。如果輸入數組中有兩個或更多匹配值,則僅替換第一個。這是一個簡單的辦法,雖然,只是刪除return語句:

public static void replace(int[] in, int find, int replace) { 
    for (int i = 0; i < in.length; i++) { 
     if (in[i] == find) { 
      in[i] = replace; 
     } 
    } 
} 
0

我認爲,如果你刪除return;線,則程序將正常工作。 return將導致該方法立即停止。因此,您的代碼無法正常工作的原因是該方法在檢查第一個項目後才停止。而且,記得的int[]返回類型添加到方法:

public static int[] replace(int[] in, int find, int replace) { 
     for (int i = 0; i < in.length; i++) { 
      if (in[i] == find) { 
       in[i] = replace; 
      } 
     } 
     return in; 
} 

然而,這裏是新的流API的替代解決方案:

public static int[] replace(int[] in, int find, int replace) { 
    return Arrays.stream(in).map(x -> x == find ? replace : x).toArray(); 
}