java为什么会出现“缺少返回语句”错误?
如果数组中的前4个元素中有一个是9,则该方法应该返回true。数组长度可能小于4。在我的方法中,由于某种原因,我不断得到“缺少返回语句错误”
public boolean arrayFront9(int[] nums) {
if (nums.length < 4) {
int counter = 0;
while (counter != nums.length) {
if (nums[counter] == 9) {
return true;
}else{
counter = counter + 1;
}
} if (counter > nums.length) {
return false;
}
}else{
int counter = 0;
while (counter <= 4) {
if (nums[counter] == 9) {
return true;
}else{
counter = counter + 1;
} if (counter > 4) {
return false;
}
}
}
}
`
我知道我必须确保,无论代码有什么返回值,但给定if和else语句,数组的长度要么小于4,要么大于或等于4,所以无论呈现什么数组,它都应该输入这些条件之一
# 1 楼答案
试试这个
实际上,你没有在方法中返回任何东西,而是在if/else中返回
# 2 楼答案
正如一条评论所说,您的一条代码路径没有返回值
这要简单得多