This is a simple array question, not for homework, just for general knowledge before I take another programming class next fall.
Given an array of ints, return true if 6 appears as either the first or last element in the array. The array will be length 1 or more.
firstLast6({1, 2, 6}) → true
firstLast6({6, 1, 2, 3}) → true
firstLast6({3, 2, 1}) → false
The problem I have is that you are not supposed to use any loops to traverse the array. How can this be written to avoid an index out of bounds exception if I don't know the total number of ints in the input data?
My solution --- it works but not exactly the answer they were looking for.
public boolean firstLast6(int[] nums) {
for (int i=0; i < (nums.length ); i++)
{
if (i == 0 && nums[i] == 6)
{
return true;
}
else if (i == (nums.length - 1) && nums[i] ==6)
{
return true;
}
}
return false;
}
nums.lengththen whats the problem?? just use nums[0] for first element and nums[nums.length-1] for last element.