为了账号安全,请及时绑定邮箱和手机立即绑定

我似乎在代码中找不到任何逻辑错误,但它仍然没有按预期工作

我似乎在代码中找不到任何逻辑错误,但它仍然没有按预期工作

拉莫斯之舞 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 关注
  • 106 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信