【发布时间】:2016-10-30 18:19:07
【问题描述】:
我目前正在codingbat 网站上做一个练习,上面写着:
给定一个整数数组,如果数组包含 6,则递归计算。 我们将使用只考虑数组的一部分的约定 从给定索引开始。这样一个递归调用就可以通过 index+1 向下移动数组。初始调用将传入索引为 0.
示例:
array6([1, 6, 4], 0) → true
array6([1, 4], 0) → false
array6([6], 0) → true
我的解决方案如下,但由于某种原因,当我的if(nums[index] == 6) 为真时,它仍会执行else block. 中的代码
我的问题:
从技术上讲,当if statement 中的代码被执行时,它不应该执行else block 中的代码。那为什么会持续存在呢?;
public static boolean array6(int[] nums, int index) {
if(nums.length == 0){
return false;
}
if(index == nums.length-1 && nums[index] != 6){
return false;
}
if(index == nums.length-1 && nums[index] == 6){
return true;
}
if(nums[index] == 6){
return true;
}else{
array6(nums,index+1);
}
return false;
}
【问题讨论】: