簡體   English   中英

我似乎在代碼中找不到任何邏輯錯誤,但仍無法按預期工作

[英]I can't seem to find any logic errors in the code, but it still doesn't work as expected

給定一個整數數組,如果值3恰好出現在數組中3次且沒有3個相鄰,則返回true。

我只是一個初學者,在編碼技巧課程上遇到了一些麻煩。 邏輯似乎很好。 我已經向“橡皮鴨”解釋了1000次,但我發現它沒有問題。 除“其他測試”選項卡外,所有的codingbat測試均按預期運行,我無法看到數組中的特定數字,也無法與代碼進行比較。 我對此感到非常困惑,希望您能幫助我!

public boolean haveThree(int[] a) {

    int count = 0;           //to count the appearences of 3
    boolean doLado = false;   //to check if a 3 is next to another 3

    if(a[0] == 3)    // check if first index is 3
        count++;      // add one if it is

    for(int i=1; i<a.length ; i++) { //loop starting at 1 to check rest of array

        if(a[i] == 3) {     // check if i is 3
            if(a[i-1] == a[i]) // if i its 3, check if the previous index was also 3
                return false;   // if it was indeed {..,3,3,..} return false
            else
                count++;        // else add 1 to the counter
        }
    }

    if(count == 3) //if counter of 3s equals 3 return true
        return true;

    return false; //else return false
}


tests                                  Expected  Run        
haveThree([3, 1, 3, 1, 3])----------- → true    true    OK  
haveThree([3, 1, 3, 3])---------------→ false   false   OK  
haveThree([3, 4, 3, 3, 4])------------→ false   false   OK  
haveThree([1, 3, 1, 3, 1, 2])---------→ false   false   OK  
haveThree([1, 3, 1, 3, 1, 3])---------→ true    true    OK  
haveThree([1, 3, 3, 1, 3])------------→ false   false   OK  
haveThree([1, 3, 1, 3, 1, 3, 4, 3])---→ false   false   OK  
haveThree([3, 4, 3, 4, 3, 4, 4])----- → true    true    OK  
haveThree([3, 3, 3])------------------→ false   false   OK  
haveThree([1, 3])---------------------→ false   false   OK  
haveThree([3])------------------------→ false   false   OK  
haveThree([1])------------------------→ false   false   OK  

other tests-----------------------------X

您不會處理null ,也不會使用doLado 還你不需要的if在年底測試count == 3 我將其簡化為

public boolean haveThree(int[] a) {
    if (a == null || a.length < 3) {
        return false;
    }
    int count = 0;
    for (int i = 0; i < a.length; i++) {
        if (a[i] == 3) {
            if (i > 0 && a[i - 1] == 3) {
                return false;
            }
            count++;
        }
    }
    return count == 3;
}

代碼中缺少空檢查以檢查數組a是否為空。

如果單獨添加null檢查,則代碼將正常工作。

暫無
暫無

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

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