package com.xiaojie.arrary;
public class ArraryDemo01 {
//变量的类型 变量的名字 = 变量的值
//数组类型
public static void main(String[] args) {
int[] nums; //1.声明一个数组
int nums2[]; //同上,两种方法声明数组
nums = new int[10]; //2.创建一个数组,分配空间,里面可以放10个int类型的元素
//第一步和第二步整合
int[] nums3 = new int[10];
//3.给数组元素中赋值
nums[0] = 1;
nums[1] = 2;
nums[2] = 3;
nums[3] = 4;
nums[4] = 5;
nums[5] = 6;
nums[6] = 7;
nums[7] = 8;
//计算所有元素的和
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum = sum + nums[i];
}
System.out.println("合计:"+sum);
}
}
根据创建数组时所分配的空间进行存取数据,超出所分配空间的范围会报错
package com.xiaojie.arrary;
public class ArrayDemo02 {
public static void main(String[] args) {
//静态初始化:创建 + 赋值
int[] a= {1,2,3,4,5,6,7,8,9};
//引用类型 new 调用 Man 类
Man[] mans = {new Man(),new Man()};
//动态初始化:包含默认初始化
int[] b = new int[10];
b[0] = 10;
System.out.println(b[0]);
}
}
package com.xiaojie.arrary;
public class ArrayDemo03 {
public static void main(String[] args) {
int[] arrays = {1,2,3,4,5,6,7,8};
//打印全部的数组元素
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 += arrays[i];
}
System.out.println("sum = "+sum);
System.out.println("==============================");
//查找最大元素
int max = arrays[0];
for (int i = 0; i < arrays.length; i++) {
if (arrays[i] > max) {
max = arrays[i];
}
}
System.out.println("max = "+max);
}
}
package com.xiaojie.arrary;
public class ArrayDemo04 {
public static void main(String[] args) {
int[] arrays = {1, 2, 3, 4, 5, 6, 7, 8};
int[] reverse = reverse(arrays); //给数组类型的方法传参
printArray(reverse);
}
//反转数组
public static int[] reverse(int[] arrays) { //返回数组前,方法要是数组类型 返回一个数组,格式是 int[] reverse
int[] result = new int[arrays.length]; //创建result的数组
//反转的操作
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]);
}
}
//JDK1.5,没有下标
// for (int array : arrays) {
// System.out.println(array);
// }
}