编写采用数组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;
}
}
答案 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;
}