This is the question in Coding bat(the Java version):: Given an array of ints, return true if the array contains a 2 next to a 2 somewhere. has22({1, 2, 2}) → true has22({1, 2, 1, 2}) → false has22({2, 1, 2}) → false
This was my solution:
public boolean has22(int[] nums) {
for (int i=0; i<nums.length-1;i++) {
if (nums[i]==2 && nums[i+1]==2) {
return true;
}
else {
return false;
}
}
}
Doesn't compile while this does..
public boolean has22(int[] nums) {
for (int i=0; i<nums.length-1;i++) {
if (nums[i]==2 && nums[i+1]==2) {
return true;
}
else {
}
}
return false;
}
Sorry if this is a stupid question but I'm confused about the brackets at the end.
Imagine a case when your argument is empty or
null
. Your first method doesn't compile, because it doesn't return aboolean
value for all cases.Your second method compiles, because it will return a
boolean
value in any case, after the iteration is complete.