写一个类在其中定义一些方法实现数组元素的遍历、排序、插入、删除、查找。
public class ArrayTest{
public static void main(String[] args){
int[] a={11,2,-3,54,115,36};
int[] b={110,-9,78,27,6,225,94,32,-12,1111,0};
//调用处理数组的方法
print(a);
}
//遍历数组元素的方法
public void print(int[] a){
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
//对数组元素进行排序的方法
public int[] sort(int[] a){
for(int i=0;i<a.length-1;i++){
for(int j=i+1;j<a.length;j++){
if(a[i]<a[j]){
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
return a;
}
//找出数组中值最大的元素
public int maxValue(int[] a){
int temp=a[0];
for(int i=1;i<a.length;i++){
if(temp<a[i])
temp=a[i];
}
return temp;
}
//求数组元素的和
public int sum(int[] a){
int sum=0;
for(int i=0;i<a.length;i++){
sum+=a[i];
}
return sum;
}
//将数组中的元素逆序排列
public int[] reverse(int[] a){
for(int i=0;i<a.length/2;i++){
int temp=a[i];
a[i]=a[a.length-i-1];
a[a.length-i-1]=temp;
}
return a;
}
}
这是一个 Java 类 ArrayTest
,它包含了对数组进行不同操作的方法。以下是代码的解析:
-
public class ArrayTest
:定义一个公共类ArrayTest
。 -
public static void main(String[] args)
:程序的主方法。 -
创建一个数组
a
,并初始化其值。 -
调用
print(a)
方法,输出数组a
的所有元素。 -
public void print(int[] a)
:遍历数组元素的方法。- 使用循环遍历数组
a
的所有元素,并打印每个元素的值。
- 使用循环遍历数组
-
public int[] sort(int[] a)
:对数组元素进行排序的方法。- 使用双重循环进行选择排序,将数组
a
中的元素按降序排列。
- 使用双重循环进行选择排序,将数组
-
public int maxValue(int[] a)
:找出数组中值最大的元素。- 使用循环遍历数组
a
的所有元素,找出最大的元素并返回。
- 使用循环遍历数组
-
public int sum(int[] a)
:求数组元素的和。- 使用循环遍历数组
a
的所有元素,将所有元素相加并返回总和。
- 使用循环遍历数组
-
public int[] reverse(int[] a)
:将数组中的元素逆序排列。- 使用循环将数组
a
的元素逆序排列,并返回逆序后的数组。
- 使用循环将数组
通过这段代码,您可以对数组进行打印、排序、求最大值、求和以及逆序排列等操作。在主方法中,示例了如何使用这些方法对数组进行操作并输出结果。