package com.jiemyx.array;
public class ArrayDemo04 {
public static void main(String[] args) {
int[] arrays = {1,2,3,4,5};
//打印全部的数组元素
for (int i = 0; i < arrays.length; i++) {
System.out.println(arrays[i]);
}
System.out.println("============");
//计算所有元素的和
int sum = 0;
for (int i = 0; i < arrays.length; i++) {
sum = sum + arrays[i];
}
System.out.println(sum);
System.out.println("=============");
//查找最大元素
int max = arrays[0];
for (int i = 1; i < arrays.length; i++) {
if (max < arrays[i]){
max = arrays[i];
}
}
System.out.println(max);
}
}
package com.jiemyx.array;
public class ArrayDemo05 {
public static void main(String[] args) {
int[] a = {1,2,3,4,5,6};
//JDK1.5开始有的增强型for循环,但是没有下标
for (int i : a) {
System.out.println(i);
}
System.out.println("==========");
//打印数组元素的方法
printArray(a);
System.out.println();
System.out.println("============");
//反转数组
int[] b = reverse(a);
printArray(b);
}
//数组作方法入参:定义一个打印数组元素的方法
public static void printArray(int[] arrays){
for (int i = 0; i < arrays.length; i++) {
System.out.print(arrays[i] + " ");
}
}
//数组作返回值:反转数组
public static int[] reverse(int[] arrays){
int[] result = new int[arrays.length];
for (int i = 0,j = result.length-1; i < arrays.length; i++,j--) {
result[j] = arrays[i];
}
return result;
}
}
原文:https://www.cnblogs.com/Jiemyx/p/14608185.html