Array usage
-
For loop
-
For each loop
-
Array as method input parameter
For loop
package com.HuoLong.array;
public class ArrayDemo03 {
public static void main(String[] args) {
int[] array={1,2,3,4,5};//Write dead
//Print all array elements
for (int i = 0; i <array.length ; i++) {
System.out.println(array[i]);
}
System.out.println("============");
//Calculate the sum of all elements
int sum=0;
for (int i = 0; i < array.length ; i++) {
sum=sum+array[i];
}
System.out.println("sum="+sum);
System.out.println("============");
//Find maximum element
int max=array[0];
for (int i = 1; i <array.length ; i++) {
if (array[i]>max){
max=array[i];
}
}System.out.println("max="+max);
}}
For each loop
First, define an array int [] arrays = {1,2,3,4,5}; Then arrays For + space, and then the output is array, as follows:
public class ArrayDemo04 {
public static void main(String[] args) {
int[] arrays={1,2,3,4,5};
//Enhanced for loop # for printout
for (int array : arrays) {
System.out.println(array);
}//For each loop
Array as method input parameter
Define a printarray method below. Write int [] arrays (arguments) for the parameters of the method (int [] arrays = {1, 2, 3, 4, 5} has been established in the main method), then write the method body in the method, call it in the main method and output.
package com.HuoLong.array;
public class ArrayDemo04 {
public static void main(String[] args) {
int[] arrays={1,2,3,4,5};
printArray(arrays);
}
/// / print array elements
public static void printArray(int[] arrays){
for (int i = 0; i < arrays.length; i++) {
System.out.print(arrays[i]+" ");
}
}
}
Return value as array
Generally, this kind of inversion array is used. Modify the contents of the array, and then return a new array, as follows:
package com.HuoLong.array;
//Reverse return value name
//Printarrays array can be called as an input parameter
public class ArrayDemo04 {
public static void main(String[] args) {
int[] arrays={1,2,3,4,5};
//Enhanced for loop # for printout
// for (int array : arrays) {
//// System.out.println(array);
//} / / for each loop
// printArray(arrays);
int[] reverses = reverse(arrays);
printArray(reverses);
}
public static int[] reverse(int[] arrays){
int[] result=new int[arrays.length];
for (int i = 0,j= arrays.length-1; i < arrays.length; i++,j--) {
result[j]=arrays[i];
}
return result;
}
/// / print array elements
public static void printArray(int[] arrays){
for (int array : arrays) {
System.out.print(array + " ");
}
}
}