数组的使用
package array;
public class Demo02 {
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]);
}
//计算所有元素的和
int sum = 0;
for (int i=0;i<arrays.length;i++){
sum = sum +arrays[i];
}
System.out.println("sum="+sum);
//查找最大元素
int max = arrays[0];
for (int i = 1; i <arrays.length;i++){
if(arrays[i]>max){
max = arrays[i];
}
}
System.out.println("max="+max);
}
}
package array;
public class Demo03 {
public static void main(String[] args) {
int[] arrays = {1,2,3,4,5};
int[] reverse = reverse(arrays);
printArray(reverse);
}
// 反转数组
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;
}
//打印数组元素
public static void printArray(int[] arrays){
for (int i = 0; i < arrays.length; i++) {
System.out.print(arrays[i]+" ");
}
}
}
多维数组
定义
int a[][] = new int [2][5];
package array;
public class Demo04 {
public static void main(String[] args) {
int[][] array = {{1,2},{2,3},{3,4},{4,5}};
/*
1,2 array[0]
2,3 array[1]
3,4 array[2]
4,5 array[3]
*/
//打印数组元素
for (int i = 0; i < array.length ; i++) {
for (int j = 0; j <array[i].length ; j++) {
System.out.println(array[i][j]);
}
}
}
}