亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

拉莫斯之舞 2023-05-24 16:28:08
給定一個整數數組,如果值 3 在數組中恰好出現 3 次,并且沒有 3 彼此相鄰,則返回 true。我只是一個初學者,在 codingbat 課程上遇到了一些麻煩。邏輯似乎沒問題。我跟“橡皮鴨”解釋了一千遍,沒發現問題。所有 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
查看完整描述

2 回答

?
慕森王

TA貢獻1777條經驗 獲得超3個贊

你不處理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;

}


查看完整回答
反對 回復 2023-05-24
?
森欄

TA貢獻1810條經驗 獲得超5個贊

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

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


查看完整回答
反對 回復 2023-05-24
  • 2 回答
  • 0 關注
  • 172 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號