簡體   English   中英

復制數組並更改值? 有人能告訴我我的代碼有什么問題嗎

[英]Copying an array and changing the values? Can someone tell me what is wrong with my code

編寫一個方法,該方法引用一個整數值數組和兩個整數 oldVal 和 newVal,並創建並返回一個新數組,該數組是原始數組的副本,但其中所有出現的值 oldVal 都被替換為值 newVal。

誰能告訴我我做錯了什么?

public static int[] copyReplace(int[] values, int oldVal, int newVal) {
    int[] b = values.length;
    for (int i = 0; i < values.length; i++) {
        if (values[i] == oldVal) {
            oldVal = newVal;
        }
        b[i] = values[i];
    }
    return b;
}

首先,這不是創建數組的正確方法:

int[] b = values.length;

我假設您正在嘗試創建該長度的數組:

int[] b = new int[values.length];

此外,即使您進行此更改,此行也不會執行您認為的操作:

oldVal = newVal;

這不會對數組中的值產生任何影響 - 您所做的只是更改局部變量。 我假設你打算做這樣的事情:

if(values[i] == oldVal){
    b[i] = newVal;                   
}
else
{
    b[i] = values[i]
}

這里有兩件事是錯誤的,我可以立即看到。

首先你不能設置b = values.length; b 是一個數組, values.length 是一個整數。 如果您的意圖是復制數組,則應該這樣做。 b = values; .

接下來,在 forloop 中,您只需將舊值整數設置為新值。 oldVal = newVal應該改為values[i] = newVal 但是,這將更改您的原始數組,而不是您應該返回的新數組。 所以它應該是b[i] = newVal;

最終產品應該是這樣的:

public static int[] copyReplace(int[] values, int oldVal, int newVal){

       int[] b = values;

        for(int i = 0; i < values.length; i++){

            if(values[i] == oldVal){

                b[i] = newVal;                   
            }          
    }

    return b;                
}

這是我的解決方案和一些評論

public static int[] copyReplace(int[] values, int oldVal, int newVal){

   //Here when you declare b, you need to declare it as an int[]
   //You declared yours as just a plain old integer rather than an array 
   //with the size you want
   int[] b = new int[values.length];


    for(int i = 0; i < values.length; i++){

        if(values[i] == oldVal){
            //You had the correct if statement but what you really want to 
            //be doing is copying the desired value into the new array
            b[i] = newVal;

        } else {
            //The other case is to keep the value the same as the old array
            b[i] = values[i];
        }
    }
   return b;
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM