英文:
Error even after adding return statement in each condition
问题
Added return statement for all combinations of if and else, still getting missing return statement error. Below is the code:
为所有的 if 和 else 组合添加了返回语句,仍然出现缺少返回语句的错误。以下是代码:
public int searchInsert(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] <= target) {
if (nums[i] == target)
return i;
else
return i + 1;
} else
return i;
}
}
英文:
Added return statement for all combinations of if and else, still getting missing return statement error. Below is the code:
public int searchInsert(int[] nums, int target) {
for(int i=0;i<nums.length;i++){
if(nums[i] <= target){
if(nums[i] == target)
return i;
else
return i+1;
}
else
return i;
}
}
答案1
得分: 1
两个return语句都在if结构内。在for循环之外的主块内没有返回。
英文:
Both your return statements are within the if construct. There is no return within the main block outside of the for loop.
答案2
得分: 1
从句法上看,这可能有效,但在编译时,编译器期望在for循环外部有一个返回语句。即使它是"return null",也可以。
英文:
Syntactically, this might work but at the compile time, compiler expects a return statement outside for loop. Even it it’s “return null”, it’s fine.
答案3
得分: 1
你似乎感到困惑。你粘贴的代码没有执行任何操作。具体来说,由于每条路径通过'for'返回,因此此for循环将分析nums[0],这就是它将要做的全部工作:如果nums[0]等于或高于目标值,则返回0,如果不是,则返回1。
javac无法编译此代码,因为您的代码没有说明如果nums为空时应返回什么。您添加了不必要的返回语句。您可能想要删除最后的else return i;
部分,并在底部添加return nums.length;
(这是回答问题的答案:如果nums数组完全为空,或者所有元素都高于目标值,则应在哪个索引处插入?)。
英文:
You seem confused. The code you pasted doesn't do anything. Specifically, because every path through the 'for' returns, this for loop is going to analyse nums[0], and that's all it'll ever do: if nums[0] is equal or higher than target, it returns 0, and if it is not, it returns 1.
javac can't compile this because your code doesn't say what should be returned if nums is empty. You've added returns that you shouldn't. Presumably what you want is to get rid of the last else return i;
part, and add at the very bottom return nums.length;
(which is the answer to the question: At what index should I insert, if the nums array is completely empty, or, ALL elements are higher than target?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论