gpt4 book ai didi

java - 递归方法的问题

转载 作者:行者123 更新时间:2023-11-30 06:21:56 27 4
gpt4 key购买 nike

public static boolean array6(int[] nums, int index) {
if(nums.length > index+1)
{
if(nums[index] == 6)
return true;
else
array6(nums,index+1);
}
else if(nums.length==index+1)
{
if(nums[index] == 6)
return true;
else
return false;
}
return false;
}

作为我的 CSA 类(class)练习的一部分,我们必须编写一个方法来查找 int 数组中是否存在 6 并返回相应的 boolean 值。如果数组中的第一个数字是 6,我编写的方法有效,但其他情况则无效。为什么?

注意:必须递归完成

最佳答案

问题是您没有触发递归,因为您的代码中没有任何地方可以返回方法本身的结果。重写如果条件为 true 则执行的 if 语句的内容,如下所示,将使其按预期工作:

if (nums.length > index_next) 
{
if (nums[index] == 6)
return true;

// you have to return the result of the function here
// in order to obtain an effective recursion, otherwise the
// method is called but it's output value is ignored and the
// functions goes outside the scope of the if statement
// reaching the "return false" located at the bottom
return array6(nums, index_next);
}

但总的来说,你的函数存在很多问题。您的任务非常简单,但您正在以极其复杂的方式对其进行编码。您可以使用许多内置函数来达到相同的结果...即使您不想使用它们,一个简单的 for 循环 也可以完成这项工作:

boolean found = false;

for (int i = 0; i < nums.length; ++i)
{
if (nums[i] == 6)
{
found = true;
break;
}
}

编辑:递归实现

public static boolean array6(int[] nums, int index)
{
if (index == nums.length)
return false;

if (nums[index] == 6)
return true;

return array6(nums, index + 1);
}

关于java - 递归方法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47964430/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com