数组的简单操作
public class arrayDemo03 {
public static void main(String[] args) {
int[] array = {1,2,3,4,5};
//打印数组元素
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
//计算所有元素的和
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
System.out.println("数组的和为:" + sum);
//查找最大元素
int max = array[0];
for (int i = 0; i < array.length; i++) {
if (max < array[i]){
max = array[i];
}
}
System.out.println("数组中最大元素为" + max);
}
}
public class arrayDemo04 {
public static void main(String[] args) {
int[] arrays = {1,2,3,4,5};
// for-each 增强型for循环 适合打印输出,不适合造作内部元素
// 数组名.for 可在idea中自动生成 JDK1.5版本以上才可以实现 无法对下标进行操作
for (int array : arrays) {
System.out.println(array);
}
printArray(arrays);
System.out.println();
int[] result = reverse(arrays);
for (int i = 0; i < result.length; i++) {
System.out.print( result[i] + " ");
}
}
// 反转数组
public static int[] reverse(int[] arrays){
int [] result = new int[arrays.length];
for (int i = arrays.length-1,j=0; i < arrays.length && j < arrays.length; i--,j++) {
result[j] = arrays[i];
}
return result;
}
//打印数组元素
public static void printArray(int[] arrays){
for (int i = 0; i < arrays.length; i++) {
System.out.print( arrays[i] + " ");
}
}
}
标签:int,System,arrays,length,数组,简单,操作,array,out
From: https://www.cnblogs.com/GXEndeavor/p/18675258