Java零基础入门Day4:数组与二维数组详解
一、为什么需要数组?
当程序需要处理批量同类型数据时,使用多个变量存储会非常繁琐。例如存储70个学生姓名时,需定义70个变量,而数组可以简化这一过程,提高代码可维护性。
示例:变量存储的弊端
String name1 = "张誉";
String name2 = "刘疏桐";
// ... 定义70个变量
String name70 = "陈侃";
二、一维数组
1. 数组的定义与初始化
-
静态初始化:定义时直接赋值
// 完整格式 String[] names = new String[]{"张三", "李四", "王五", "赵六", "孙七", "周八", "吴九"}; // 简化格式 int[] scores = {85, 90, 78, 92, 88};
-
动态初始化:先定义长度,后赋值
double[] javaScores = new double[8]; // 定义长度为8的数组 javaScores[0] = 89.5; // 后续逐个赋值
2. 数组的访问与遍历
-
访问元素:通过索引(从0开始)
System.out.println(names[0]); // 输出:张三 names[1] = "田启峰"; // 修改元素
-
遍历数组
for (int i = 0; i < names.length; i++) {System.out.println(names[i]); }
3. 常见应用案例
案例1:随机点名
String[] names = {"张三", "李四", "王五", "赵六", "孙七", "周八", "吴九"};
int index = (int) (Math.random() * names.length);
System.out.println(names[index] + "出来回答问题!");
案例2:统计成绩(最高分、最低分、平均分)
double[] scores = {85, 90, 78, 92, 88};
double max = scores[0], min = scores[0], sum = 0;for (double score : scores) {if (score > max) max = score;if (score < min) min = score;sum += score;
}
double avg = sum / scores.length;System.out.println("最高分:" + max);
System.out.println("最低分:" + min);
System.out.println("平均分:" + avg);
三、二维数组
1. 定义与初始化
-
静态初始化
String[][] seats = {{"张无忌", "赵敏", "周芷若"},{"张三丰", "宋远桥", "殷梨亭"},{"灭绝", "陈昆", "玄冥二老", "金毛狮王"},{"杨逍", "纪晓芙"} };
-
动态初始化
int[][] matrix = new int[3][5]; // 3行5列的二维数组
2. 访问与遍历
-
访问元素
System.out.println(seats[0][1]); // 输出:赵敏 seats[2][2] = "谢逊"; // 修改元素
-
遍历二维数组
for (int i = 0; i < seats.length; i++) {for (int j = 0; j < seats[i].length; j++) {System.out.print(seats[i][j] + "\t");}System.out.println(); }
3. 应用案例:斗地主洗牌
// 初始化54张牌
String[] colors = {"♠", "♥", "♣", "♦"};
String[] numbers = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
String[] poker = new String[54];
int index = 0;for (String number : numbers) {for (String color : colors) {poker[index++] = color + number;}
}
poker[52] = "小王";
poker[53] = "大王";// 洗牌:随机交换元素
Random rand = new Random();
for (int i = 0; i < poker.length; i++) {int swapIndex = rand.nextInt(poker.length);String temp = poker[i];poker[i] = poker[swapIndex];poker[swapIndex] = temp;
}
四、总结
-
数组是存储同类型数据的容器,可显著简化批量数据操作。
-
一维数组通过索引访问,二维数组可表示表格或矩阵结构。
-
实际开发中,数组常用于游戏、数据处理、算法等领域。