开发者

Simple Java array question

Codingbat.com array question

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;
}


You would use the length property to access the last index:

public boolean firstLast6(int[] nums) {
    if (nums == null || nums.length == 0) {
        return false;
    }

    return nums[0] == 6 || nums[nums.length - 1] == 6;
}

EDIT: added check for null or empty array.


Simply retrieve the first array element, and the last array element. That is:

nums[0]
nums[nums.length - 1];


Hey , you don't need any loops for this . All you have to do is :

if(array[0]==6 || array[array.length-1]==6){
    return true ;
}
  else{
     return false ; 
 }


The most compact and efficient expression of this would be

public void firstLast(int[] a) {
  return a.length > 0 && (a[0] == 6 || a[a.length-1] == 6);
}


the output can be easily obtained by

if(array[0]==6||array[nums.length]==6)
return true;
else
return false;


this is full code for this problem,i hope this gonna help you

import java.util.Scanner;


public class pair13 {


public static void main(String[] args) {

    int[] number=new int[6];



    Scanner ss=new Scanner(System.in);

    for (int j = 0; j < number.length; j++) {
        number[j]=ss.nextInt();

    }

    firstLast6( number);
    System.out.print(firstLast6(number));
}



 public static boolean firstLast6( int[] nums ) {

     if ( nums[0]==6 || nums[nums.length-1]==6 ){
                   return true;
     }
     else{

         return false;

     }
}




}


This code works fine.

public boolean firstLast6(int[] nums) {
      int length=nums.length;
      if(nums[0]==6||nums[length-1]==6){
        return true;
      }
      return false;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜