数组使用
1.打印全部元素
int[] arrays = {1,2,3,4,5};
for (int i = 0; i < arrays.length; i++) {
System.out.println(arrays[i]);
}
//强化for循环,这个循环中的元素没有下标
for (int array : arrays) {
System.out.println(array);
}
2.计算元素和
int[] arrays = {1,2,3,4,5};
int sum = 0;
for (int i = 0; i < arrays.length; i++) {
sum += arrays[i];
}
System.out.println("sum=" + sum);
3.查找最大元素
int[] arrays = {1,2,3,4,5};
int max = arrays[0];
for (int i = 0; i < arrays.length; i++) {
if(arrays[i] > max){
max = arrays[i];
}
}
System.out.println("max=" + max);
4.调用方法打印数组
public static void main(String[] args) {
int[] arrays = {1,2,3,4,5};
printArray(arrays);
}
public static void printArray(int[] arrays){
for (int i = 0; i < arrays.length; i++) {
System.out.println(arrays[i] + " ");
}
}
5.调用方法反转数组并打印
public static void main(String[] args) {
int[] arrays = {1,2,3,4,5};
int[] reverse = reverse(arrays);
printArray(reverse);
}
public static void printArray(int[] arrays){
for (int i = 0; i < arrays.length; i++) {
System.out.println(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;
}