计算机二级JAVA实例编程练习题5(附答案)
来源:优易学  2011-10-29 12:03:13   【优易学:中国教育考试门户网】   资料下载   IT书店

  题目:写一个Array的工具类,含有toString、Max、Min、Average、Merg、isExist、equals、find等操作。
  答:
  package util;
  import java.util.ArrayList;
  import java.util.Arrays;
  import java.util.List;
  /**
  * @author daniel
  * Array util
  */
  public class ArrayUtil {
  /**
  * ToString
  * @param array
  * @return
  */
  public static String getToString(Object[] array){
  StringBuffer sb=new StringBuffer("{");
  for(int i=0;i
  sb.append(array[i].toString());
  if(i!=array.length-1){
  sb.append(",");
  }
  }
  sb.append("}");
  return sb.toString();
  }
  /**
  * Get the max item's key
  * @param array
  * @return
  */
  public static int maxKey(int[] array){
  int maxId=-1;
  for (int i = 0; i < array.length; i++) {
  if (maxId==-1 || array[i]>array[maxId]) {
  maxId=i;
  }
  }
  return maxId;
  }
  /**
  * Get the min item's key
  * @param array
  * @return
  */

  public static int minKey(int[] array){
  int minId=-1;
  for (int i = 0; i < array.length; i++) {
  if (minId==-1 || array[i]
  minId=i;
  }
  }
  return minId;
  }
  /**
  * Get the average of the int array
  * @param array
  * @return
  */
  public static int average(int[] array){
  int sum=0;
  if (array.length==0) {
  throw new IllegalArgumentException("Array length is zero!");
  }
  for (int i = 0; i < array.length; i++) {
  sum+=array[i];
  }
  return sum/array.length;
  }
  /**
  * merg two array to one
  * @param one
  * @param other
  * @return
  */
  public static Object[] merg(Object[] one,Object[] other){
  Object[][] tmp=new Object[][]{one,other};
  Object[] result=null;
  List res=null;
  int size = 0;
  for (int i = 0; i < tmp.length; i++) {
  size+=tmp[i].length;
  }
  res=new ArrayList(size);
  for (int i = 0; i < tmp.length; i++) {
  for (int j = 0; j < tmp[i].length; j++) {
  res.add(tmp[i][j]);
  }
  }
  return res.toArray();
  }
  /**
  * Check value exists
  * @param array
  * @param item
  * @return
  */

 public static boolean exists (Object[] array, Object item) {
  if (item==null) {
  return false;
  }
  List list=Arrays.asList(array);
  return list.contains(item);
  }
  /**
  * Test
  * @param args
  */
  public static void main(String[] args) {
  Object[] obj=new Object[]{0,1,"zhou",2,3,4,5,6,"daniel"};
  //toString
  System.out.println(getToString(obj));
  //get max
  int[] values=new int[]{0,1,2,3,4,5,6,8,33,2};
  System.out.println(values[maxKey(values)]);
  //get min
  System.out.println(values[minKey(values)]);
  //get average
  System.out.println(average(values));
  //merg two array to one
  Object[] object=new Object[]{203,15,26,"jack"};
  Object[] all= merg(obj,object);
  System.out.println(getToString(all));
  //check value exist in array
  System.out.println(exists(obj,"daniel"));
  }
  }

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训