数组是存储多个相同类型数据的容器
数组的声明和初始化
代码示例1:数组基础
public class ArrayBasics {
public static void main(String[] args) {
System.out.println("=== 数组基础示例 ===");
// 方式1:先声明,后初始化
System.out.println("\n1. 方式一:先声明,后初始化");
int[] scores; // 声明一个整型数组
scores = new int[5]; // 创建可以存储5个整数的数组
// 给数组元素赋值
scores[0] = 85;
scores[1] = 92;
scores[2] = 78;
scores[3] = 90;
scores[4] = 88;
System.out.println("第一个学生成绩: " + scores[0]);
System.out.println("第三个学生成绩: " + scores[2]);
// 方式2:声明同时初始化
System.out.println("\n2. 方式二:声明同时初始化");
String[] fruits = new String[3]; // 创建可以存储3个字符串的数组
fruits[0] = "苹果";
fruits[1] = "香蕉";
fruits[2] = "橙子";
System.out.println("第一种水果: " + fruits[0]);
System.out.println("第二种水果: " + fruits[1]);
// 方式3:直接赋值(静态初始化)
System.out.println("\n3. 方式三:直接赋值");
double[] prices = {3.5, 2.8, 4.2, 5.0}; // 直接给数组元素赋值
System.out.println("第一种商品价格: " + prices[0] + "元");
System.out.println("第二种商品价格: " + prices[1] + "元");
// 方式4:创建匿名数组
System.out.println("\n4. 方式四:匿名数组");
char[] grades = new char[]{'A', 'B', 'C', 'D', 'F'};
System.out.println("第一个等级: " + grades[0]);
System.out.println("最后一个等级: " + grades[4]);
// 数组长度
System.out.println("\n5. 数组长度");
System.out.println("成绩数组长度: " + scores.length);
System.out.println("水果数组长度: " + fruits.length);
System.out.println("价格数组长度: " + prices.length);
System.out.println("等级数组长度: " + grades.length);
}
}
运行结果:
=== 数组基础示例 ===
1. 方式一:先声明,后初始化
第一个学生成绩: 85
第三个学生成绩: 78
2. 方式二:声明同时初始化
第一种水果: 苹果
第二种水果: 香蕉
3. 方式三:直接赋值
第一种商品价格: 3.5元
第二种商品价格: 2.8元
4. 方式四:匿名数组
第一个等级: A
最后一个等级: F
5. 数组长度
成绩数组长度: 5
水果数组长度: 3
价格数组长度: 4
等级数组长度: 5
代码示例2:数组遍历
public class ArrayTraversal {
public static void main(String[] args) {
System.out.println("=== 数组遍历示例 ===");
// 创建一个学生成绩数组
int[] scores = {85, 92, 78, 90, 88, 95, 76, 89, 94, 81};
System.out.println("\n1. 使用for循环遍历:");
System.out.println("学生成绩列表:");
for (int i = 0; i < scores.length; i++) {
System.out.println("第" + (i + 1) + "个学生成绩: " + scores[i] + "分");
}
System.out.println("\n2. 计算总分和平均分:");
int total = 0;
for (int i = 0; i < scores.length; i++) {
total += scores[i]; // 累加成绩
}
double average = (double) total / scores.length;
System.out.println("总分: " + total + "分");
System.out.println("平均分: " + String.format("%.2f", average) + "分");
System.out.println("\n3. 查找最高分和最低分:");
int maxScore = scores[0]; // 假设第一个是最高分
int minScore = scores[0]; // 假设第一个是最低分
for (int i = 1; i < scores.length; i++) {
if (scores[i] > maxScore) {
maxScore = scores[i];
}
if (scores[i] < minScore) {
minScore = scores[i];
}
}
System.out.println("最高分: " + maxScore + "分");
System.out.println("最低分: " + minScore + "分");
System.out.println("\n4. 使用for-each循环遍历:");
System.out.println("所有成绩:");
for (int score : scores) {
System.out.print(score + " ");
}
System.out.println(); // 换行
System.out.println("\n5. 统计及格人数:");
int passCount = 0;
for (int score : scores) {
if (score >= 60) {
passCount++;
}
}
System.out.println("及格人数: " + passCount + "人");
System.out.println("不及格人数: " + (scores.length - passCount) + "人");
}
}
运行结果:
=== 数组遍历示例 ===
1. 使用for循环遍历:
学生成绩列表:
第1个学生成绩: 85分
第2个学生成绩: 92分
第3个学生成绩: 78分
第4个学生成绩: 90分
第5个学生成绩: 88分
第6个学生成绩: 95分
第7个学生成绩: 76分
第8个学生成绩: 89分
第9个学生成绩: 94分
第10个学生成绩: 81分
2. 计算总分和平均分:
总分: 868分
平均分: 86.80分
3. 查找最高分和最低分:
最高分: 95分
最低分: 76分
4. 使用for-each循环遍历:
所有成绩:
85 92 78 90 88 95 76 89 94 81
5. 统计及格人数:
及格人数: 10人
不及格人数: 0人
代码示例3:数组的常见操作
import java.util.Arrays;
public class ArrayOperations {
public static void main(String[] args) {
System.out.println("=== 数组常见操作示例 ===");
// 创建一个数组
int[] numbers = {5, 2, 8, 1, 9, 3, 7, 4, 6};
System.out.println("原始数组: " + Arrays.toString(numbers));
// 1. 数组排序
System.out.println("\n1. 数组排序:");
int[] sortedNumbers = numbers.clone(); // 复制数组
Arrays.sort(sortedNumbers);
System.out.println("排序后: " + Arrays.toString(sortedNumbers));
// 2. 查找元素
System.out.println("\n2. 查找元素:");
int searchValue = 7;
int index = -1;
// 线性查找
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == searchValue) {
index = i;
break;
}
}
if (index != -1) {
System.out.println("找到 " + searchValue + ",在索引 " + index + " 位置");
} else {
System.out.println("未找到 " + searchValue);
}
// 使用Arrays.binarySearch(需要先排序)
Arrays.sort(numbers);
int binaryIndex = Arrays.binarySearch(numbers, searchValue);
System.out.println("二分查找 " + searchValue + ",在索引 " + binaryIndex + " 位置");
// 3. 数组复制
System.out.println("\n3. 数组复制:");
int[] copy1 = Arrays.copyOf(numbers, 5); // 复制前5个元素
System.out.println("复制前5个元素: " + Arrays.toString(copy1));
int[] copy2 = Arrays.copyOfRange(numbers, 2, 6); // 复制索引2到5的元素
System.out.println("复制索引2到5的元素: " + Arrays.toString(copy2));
// 4. 数组填充
System.out.println("\n4. 数组填充:");
int[] filledArray = new int[5];
Arrays.fill(filledArray, 10); // 所有元素填充为10
System.out.println("填充后的数组: " + Arrays.toString(filledArray));
// 部分填充
int[] partialFill = new int[10];
Arrays.fill(partialFill, 3, 7, 99); // 索引3到6填充为99
System.out.println("部分填充的数组: " + Arrays.toString(partialFill));
// 5. 数组比较
System.out.println("\n5. 数组比较:");
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
int[] arr3 = {1, 2, 4};
System.out.println("arr1 和 arr2 是否相等: " + Arrays.equals(arr1, arr2));
System.out.println("arr1 和 arr3 是否相等: " + Arrays.equals(arr1, arr3));
// 6. 数组反转
System.out.println("\n6. 数组反转:");
int[] original = {1, 2, 3, 4, 5};
System.out.println("原始数组: " + Arrays.toString(original));
// 手动反转数组
int[] reversed = new int[original.length];
for (int i = 0; i < original.length; i++) {
reversed[i] = original[original.length - 1 - i];
}
System.out.println("反转后数组: " + Arrays.toString(reversed));
}
}
运行结果:
=== 数组常见操作示例 ===
原始数组: [5, 2, 8, 1, 9, 3, 7, 4, 6]
1. 数组排序:
排序后: [1, 2, 3, 4, 5, 6, 7, 8, 9]
2. 查找元素:
找到 7,在索引 6 位置
二分查找 7,在索引 6 位置
3. 数组复制:
复制前5个元素: [1, 2, 3, 4, 5]
复制索引2到5的元素: [3, 4, 5, 6]
4. 数组填充:
填充后的数组: [10, 10, 10, 10, 10]
部分填充的数组: [0, 0, 0, 99, 99, 99, 99, 0, 0, 0]
5. 数组比较:
arr1 和 arr2 是否相等: true
arr1 和 arr3 是否相等: false
6. 数组反转:
原始数组: [1, 2, 3, 4, 5]
反转后数组: [5, 4, 3, 2, 1]
代码示例4:二维数组(数组的数组)
public class TwoDimensionalArray {
public static void main(String[] args) {
System.out.println("=== 二维数组示例 ===");
// 1. 声明和初始化二维数组
System.out.println("\n1. 二维数组基础:");
// 方式1:直接初始化
int[][] matrix1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println("二维数组 matrix1:");
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[i].length; j++) {
System.out.print(matrix1[i][j] + "\t");
}
System.out.println();
}
// 方式2:先声明,后赋值
System.out.println("\n2. 创建学生成绩表:");
// 3个学生,每个学生有4门课成绩
int[][] studentScores = new int[3][4];
// 学生1的成绩
studentScores[0][0] = 85; // 语文
studentScores[0][1] = 92; // 数学
studentScores[0][2] = 78; // 英语
studentScores[0][3] = 90; // 科学
// 学生2的成绩
studentScores[1][0] = 88;
studentScores[1][1] = 76;
studentScores[1][2] = 95;
studentScores[1][3] = 82;
// 学生3的成绩
studentScores[2][0] = 92;
studentScores[2][1] = 85;
studentScores[2][2] = 79;
studentScores[2][3] = 88;
// 显示学生成绩表
String[] subjects = {"语文", "数学", "英语", "科学"};
String[] students = {"张三", "李四", "王五"};
System.out.println("\t\t" + String.join("\t", subjects));
for (int i = 0; i < studentScores.length; i++) {
System.out.print(students[i] + "\t\t");
for (int j = 0; j < studentScores[i].length; j++) {
System.out.print(studentScores[i][j] + "\t");
}
System.out.println();
}
// 3. 计算每个学生的平均分
System.out.println("\n3. 计算每个学生的平均分:");
for (int i = 0; i < studentScores.length; i++) {
int sum = 0;
for (int j = 0; j < studentScores[i].length; j++) {
sum += studentScores[i][j];
}
double average = (double) sum / studentScores[i].length;
System.out.println(students[i] + "的平均分: " + String.format("%.2f", average));
}
// 4. 计算每门课的平均分
System.out.println("\n4. 计算每门课的平均分:");
for (int j = 0; j < studentScores[0].length; j++) {
int sum = 0;
for (int i = 0; i < studentScores.length; i++) {
sum += studentScores[i][j];
}
double average = (double) sum / studentScores.length;
System.out.println(subjects[j] + "的平均分: " + String.format("%.2f", average));
}
// 5. 不规则二维数组
System.out.println("\n5. 不规则二维数组:");
int[][] irregularArray = new int[3][];
irregularArray[0] = new int[2]; // 第一行有2个元素
irregularArray[1] = new int[3]; // 第二行有3个元素
irregularArray[2] = new int[4]; // 第三行有4个元素
// 填充数据
int value = 1;
for (int i = 0; i < irregularArray.length; i++) {
for (int j = 0; j < irregularArray[i].length; j++) {
irregularArray[i][j] = value++;
}
}
// 显示不规则数组
System.out.println("不规则数组:");
for (int i = 0; i < irregularArray.length; i++) {
System.out.print("第" + (i + 1) + "行: ");
for (int j = 0; j < irregularArray[i].length; j++) {
System.out.print(irregularArray[i][j] + " ");
}
System.out.println();
}
}
}
运行结果:
=== 二维数组示例 ===
1. 二维数组基础:
二维数组 matrix1:
1 2 3
4 5 6
7 8 9
2. 创建学生成绩表:
语文 数学 英语 科学
张三 85 92 78 90
李四 88 76 95 82
王五 92 85 79 88
3. 计算每个学生的平均分:
张三的平均分: 86.25
李四的平均分: 85.25
王五的平均分: 86.00
4. 计算每门课的平均分:
语文的平均分: 88.33
数学的平均分: 84.33
英语的平均分: 84.00
科学的平均分: 86.67
5. 不规则二维数组:
不规则数组:
第1行: 1 2
第2行: 3 4 5
第3行: 6 7 8 9
代码示例5:综合应用 - 学生成绩管理系统
import java.util.Scanner;
public class StudentGradeSystem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("=== 学生成绩管理系统 ===");
// 输入学生数量
System.out.print("请输入学生数量: ");
int studentCount = scanner.nextInt();
// 输入科目数量
System.out.print("请输入科目数量: ");
int subjectCount = scanner.nextInt();
// 创建数组
String[] studentNames = new String[studentCount];
String[] subjectNames = new String[subjectCount];
int[][] grades = new int[studentCount][subjectCount];
// 输入科目名称
System.out.println("\n=== 输入科目名称 ===");
for (int i = 0; i < subjectCount; i++) {
System.out.print("请输入第" + (i + 1) + "个科目名称: ");
subjectNames[i] = scanner.next();
}
// 输入学生信息和成绩
System.out.println("\n=== 输入学生信息和成绩 ===");
for (int i = 0; i < studentCount; i++) {
System.out.println("\n--- 第" + (i + 1) + "个学生 ---");
System.out.print("请输入学生姓名: ");
studentNames[i] = scanner.next();
System.out.println("请输入各科成绩:");
for (int j = 0; j < subjectCount; j++) {
System.out.print(subjectNames[j] + ": ");
grades[i][j] = scanner.nextInt();
}
}
// 显示成绩表
System.out.println("\n=== 学生成绩表 ===");
System.out.print("姓名\t\t");
for (String subject : subjectNames) {
System.out.print(subject + "\t");
}
System.out.println("总分\t平均分\t排名");
// 计算总分、平均分和排名
int[] totalScores = new int[studentCount];
double[] averages = new double[studentCount];
for (int i = 0; i < studentCount; i++) {
int total = 0;
for (int j = 0; j < subjectCount; j++) {
total += grades[i][j];
}
totalScores[i] = total;
averages[i] = (double) total / subjectCount;
}
// 计算排名
int[] ranks = new int[studentCount];
for (int i = 0; i < studentCount; i++) {
int rank = 1;
for (int j = 0; j < studentCount; j++) {
if (totalScores[j] > totalScores[i]) {
rank++;
}
}
ranks[i] = rank;
}
// 显示成绩
for (int i = 0; i < studentCount; i++) {
System.out.print(studentNames[i] + "\t\t");
for (int j = 0; j < subjectCount; j++) {
System.out.print(grades[i][j] + "\t");
}
System.out.print(totalScores[i] + "\t");
System.out.print(String.format("%.2f", averages[i]) + "\t");
System.out.println(ranks[i]);
}
// 统计各科目平均分
System.out.println("\n=== 各科目统计 ===");
for (int j = 0; j < subjectCount; j++) {
int subjectTotal = 0;
int subjectMax = grades[0][j];
int subjectMin = grades[0][j];
for (int i = 0; i < studentCount; i++) {
subjectTotal += grades[i][j];
if (grades[i][j] > subjectMax) {
subjectMax = grades[i][j];
}
if (grades[i][j] < subjectMin) {
subjectMin = grades[i][j];
}
}
double subjectAverage = (double) subjectTotal / studentCount;
System.out.println(subjectNames[j] + ": ");
System.out.println(" 平均分: " + String.format("%.2f", subjectAverage));
System.out.println(" 最高分: " + subjectMax);
System.out.println(" 最低分: " + subjectMin);
}
// 查找学生
System.out.print("\n请输入要查找的学生姓名: ");
String searchName = scanner.next();
boolean found = false;
for (int i = 0; i < studentCount; i++) {
if (studentNames[i].equals(searchName)) {
found = true;
System.out.println("\n=== 找到学生: " + searchName + " ===");
System.out.println("各科成绩:");
for (int j = 0; j < subjectCount; j++) {
System.out.println(subjectNames[j] + ": " + grades[i][j]);
}
System.out.println("总分: " + totalScores[i]);
System.out.println("平均分: " + String.format("%.2f", averages[i]));
System.out.println("排名: 第" + ranks[i] + "名");
break;
}
}
if (!found) {
System.out.println("未找到学生: " + searchName);
}
scanner.close();
System.out.println("\n=== 程序结束 ===");
}
}
运行结果:
=== 学生成绩管理系统 ===
请输入学生数量: 3
请输入科目数量: 3
=== 输入科目名称 ===
请输入第1个科目名称: 语文
请输入第2个科目名称: 数学
请输入第3个科目名称: 英语
=== 输入学生信息和成绩 ===
--- 第1个学生 ---
请输入学生姓名: 张三
请输入各科成绩:
语文: 85
数学: 92
英语: 78
--- 第2个学生 ---
请输入学生姓名: 李四
请输入各科成绩:
语文: 88
数学: 76
英语: 95
--- 第3个学生 ---
请输入学生姓名: 王五
请输入各科成绩:
语文: 92
数学: 85
英语: 79
=== 学生成绩表 ===
姓名 语文 数学 英语 总分 平均分 排名
张三 85 92 78 255 85.00 2
李四 88 76 95 259 86.33 1
王五 92 85 79 256 85.33 3
=== 各科目统计 ===
语文:
平均分: 88.33
最高分: 92
最低分: 85
数学:
平均分: 84.33
最高分: 92
最低分: 76
英语:
平均分: 84.00
最高分: 95
最低分: 78
请输入要查找的学生姓名: 张三
=== 找到学生: 张三 ===
各科成绩:
语文: 85
数学: 92
英语: 78
总分: 255
平均分: 85.00
排名: 第2名
=== 程序结束 ===
总结
- 一维数组 → 像一排储物柜,用单个索引访问
- 二维数组 → 像教室的座位表,用行和列两个索引访问
- 数组长度固定 → 创建时确定大小,不能动态改变
- 索引从0开始 → 第一个元素的索引是0,不是1
- 数组遍历 → 使用for循环或for-each循环访问每个元素