我想返回数组的中间三分之一

时间:2016-07-29 01:32:47

标签: java oop

编写采用数组middle()的方法int[] a并返回一个新数组,其中包含a的中间三分之一。假设a的长度是3的倍数。例如:middle({1,2,3,4,5,6})应该返回{3,4}middle({40,50,60,70,80,90}应该{60,70}

public class middle {
   public static int[] middle(int[] a) {
      int newLen = a.length/3;
      int[] mid = new int[newLen];
      for (int i = 0; i < mid.length; i++) {
         mid[i] = a[newLen+i]; 
      }
      return mid; 
   }
}

当我尝试测试上面的代码时,它不会返回中间整数。 screenshot

1 个答案:

答案 0 :(得分:-2)

检查此代码并仔细阅读说明以了解

    int[] a = { 40, 50, 60, 70, 80};
    int newLen = (a.length- 1) / 2;

    int mid[];
    if (a.length % 2 == 0) {// checking for even number
        mid = new int[2];// if even number there must be two middle number

        mid[0] = a[newLen]; // taking first middle number
        newLen++;
        mid[1] = a[newLen]; // taking second middle number
    } else {// for odd number
        mid = new int[1];// one middle number
        mid[0] = a[newLen];
    }

    for (int i = 0; i < mid.length; i++) {
        System.out.print(mid[i] + " ");

    }

使它成为一种方法

public static int[] middle(int[] a) {
    int newLen = (a.length- 1) / 2;

    int mid[];
    if (a.length % 2 == 0) {// checking for even number
        mid = new int[2];// if even number there must be two middle number

        mid[0] = a[newLen]; // taking first middle number
        newLen++;
        mid[1] = a[newLen]; // taking second middle number
    } else {// for odd number
        mid = new int[1];// one middle number
        mid[0] = a[newLen];
    }
  return mid; 
}