19-用数组保存成绩
0. 目录
- 语数外物化生的成绩怎么表示?
- 什么是数组和数组的语法
- 用数组处理 6 门课的成绩
1. 语数外物化生的成绩怎么表示?
- 用六个变量表示,如果有更多的科目怎么办?
- 如果有更多的科目怎么办?
- 如果想求出成绩最高的科目怎么办?
public class SevenScore {
public static void main(String[] args) {
// 声明六个变量, 分别代表六门科目的成绩
int YuWen = 0;
int ShuXue = 0;
int WaiYu = 0;
int WuLi = 0;
int HuaXue = 0;
int ShengWu = 0;
}
}2. 什么是数组和数组的语法
2.1 数组的特点是:
- 数组是相同类型的变量的集合,所有元素的类型都一样
- 可以指定数组包含的元素个数,最多为 int 的最大值个「我们要创建数组的时候,数组的类型大小,必须是 int」
- 元素有固定的顺序
- 每个元素都有一个固定的编号,称之为索引(index),从 0 开始递增,类型为 int
- 可以像操作变量一样读写数组中的任何一个元素
- 如果说之前的变量是一张有名字的纸,可以通过这个名字读写这个变量;数组则是一个有名字的本子。本子有一个名字,每页纸有一个页码。可以通过本子的名字和页码读写对应的数组元素
2.2 创建和使用一个数组的语法
数组元素类型[] 变量名 = new 数组元素类型[数组长度]
变量名[索引] 可以使用这个变量,可以读取也可以给它赋值
public class CreateArray {
public static void main(String[] args) {
int[] intArray = new int[9]; // new 创建、创造
System.out.println(intArray[2]);
double[] doubleArray = new double[100];
System.out.println(doubleArray[66]);
// 添加数据
intArray[0] = 0;
intArray[1] = 1;
intArray[2] = 2;
System.out.println(intArray[2]);
System.out.println(intArray.length); // 获取数组长度
}
}在我们没有给数组中的元素赋值「添加数据」,那数组内的数据类型,都是数组类型的缺省值。对于数字类型,它的缺省值是:0。
public class array_type {
public static void main(String[] args) {
int[] intArray = new int[9];
System.out.println(intArray[0]);
short[] shortArray = new short[9];
System.out.println(shortArray[0]);
double[] doubleArray = new double[9];
System.out.println(doubleArray[0]);
String[] StringArray = new String[9];
System.out.println(StringArray[0]);
}
}3. 用数组处理 6 门课的成绩
3.1 创建数组来表示 6 门课的成绩
- 创建一个大小为 6 的 double 类型的数组
- 创建一个大小为 6 的 String 数组,代表每门课的名字
- 为每门课创建一个 int 变量,值为这门课的成绩对应的数组的索引,以便操作每门课的成绩和名字
3.2 求出最高的成绩
- 创建一个大小为 6 的 double 类型的数组
- 创建一个大小为 6 的 String 数组,保存每门课的成绩
- 为每门课创建一个 int 变量,值为这门课的成绩对应的数组的索引,以便操作每门课的成绩
- 实现计算最高成绩的逻辑
public class ScoreArrayMaxScore {
public static void main(String[] args) {
// 声明六个变量, 分别代表六门科目的成绩
int YuWenIndex = 0;
int ShuXueIndex = 1;
int WaiYuIndex = 2;
int WuLiIndex = 3;
int HuaXueIndex = 4;
int ShengWuIndex = 5;
// 每门课的名字
String[] names = new String[6];
names[YuWenIndex] = "语文";
names[ShuXueIndex] = "数学";
names[WaiYuIndex] = "外语";
names[WuLiIndex] = "物理";
names[HuaXueIndex] = "化学";
names[ShengWuIndex] = "生物";
// 每门课的成绩
double[] scores = new double[6];
// 用随机数给成绩赋值
for (int i = 0; i < 6; i++) {
scores[i] = 80 + Math.random() * 20;
}
// 计算最高成绩和最高成绩对应的科目的索引
double maxScore = -1;
int maxScoreIndex = -1;
for (int i = 0; i < 6; i++) {
System.out.println(names[i] + "的成绩为" + scores[i]);
if (maxScore < scores[i]) {
maxScore = scores[i];
maxScoreIndex = i;
}
}
// 输出最高成绩科目和成绩
System.out.println("最高分的科目为" + names[maxScoreIndex] + ",成绩为:" + maxScore);
}
}那上面寻找最高分是有缺陷的,因为有可能多个科目和最高分是相同的。这个时候可以再写一个循环,找出和最大值相等的就可以。然后把找到的输出出来。——快试一试哦。
import java.util.ArrayList;
public class ScoreArrayMaxScore {
public static void main(String[] args) {
// 声明六个变量, 分别代表六门科目的成绩
int YuWenIndex = 0;
int ShuXueIndex = 1;
int WaiYuIndex = 2;
int WuLiIndex = 3;
int HuaXueIndex = 4;
int ShengWuIndex = 5;
// 每门课的名字
String[] names = new String[6];
names[YuWenIndex] = "语文";
names[ShuXueIndex] = "数学";
names[WaiYuIndex] = "外语";
names[WuLiIndex] = "物理";
names[HuaXueIndex] = "化学";
names[ShengWuIndex] = "生物";
// 每门课的成绩
double[] scores = new double[6];
// 用随机数给成绩赋值
for (int i = 0; i < 6; i++) {
scores[i] = 80 + Math.random() * 20;
}
// 计算最高成绩
double maxScore = -1;
for (int i = 0; i < 6; i++) {
System.out.println(names[i] + "的成绩为" + scores[i]);
if (maxScore < scores[i]) {
maxScore = scores[i];
}
}
// 找到所有与最高成绩相同的科目
ArrayList<String> maxScoreSubjects = new ArrayList<>();
for (int i = 0; i < 6; i++) {
if (scores[i] == maxScore) {
maxScoreSubjects.add(names[i]);
}
}
// 输出最高成绩科目和成绩
System.out.println("最高分为:" + maxScore);
System.out.println("取得最高分的科目有:" + maxScoreSubjects);
}
}4. Java 数组常见的创建方式
int[] arr; // 声明一个数组
arr = new int[5]; // 创建一个长度为5的数组int[] arr = new int[5]; // 一步完成声明和创建int[]与int的区别:int[]是数组类型,int是单个变量类型。
- 直接给数组赋初始值,省略了长度定义:
int[] arr = {1, 2, 3, 4, 5}; // 初始化为包含5个元素的数组注意
这种方式必须在声明时完成,不能单独赋值。
错误示例:
int[] arr;
arr = {1, 2, 3, 4, 5}; // 错误:不能直接给已声明的数组赋这种形式的值正确示例:
int[] arr;
arr = new int[]{1, 2, 3, 4, 5}; // 正确:需用 `new int[]` 明确创建- 只创建数组而不需要变量名(常用于直接传递数组):
printArray(new int[]{1, 2, 3, 4, 5}); // 匿名数组作为参数示例方法:
public static void printArray(int[] arr) {
for (int num : arr) {
System.out.println(num);
}
}- 创建多维数组时需注意:
- 仅定义第一维度的长度。
- 可逐级初始化。
int[][] matrix = new int[3][4]; // 创建3行4列的二维数组- 声明并逐级初始化:
int[][] matrix = new int[3][]; // 创建3行的二维数组,但列未定义
matrix[0] = new int[2]; // 第一行2列
matrix[1] = new int[3]; // 第二行3列
matrix[2] = new int[4]; // 第三行4列- 直接声明并初始化:
int[][] matrix = {
{1, 2, 3},
{4, 5},
{6, 7, 8, 9}
};Arrays 工具类创建或填充Java 提供了 java.util.Arrays 工具类,能快速填充或初始化数组。
- 填充数组
int[] arr = new int[5];
Arrays.fill(arr, 42); // 全部填充为42- 创建固定值列表
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); // 创建固定大小的列表(不完全是数组,但常用于初始化)- 布尔类型
boolean[] flags = {true, false, true}; // 直接初始化布尔数组- 引用类型
String[] names = {"Alice", "Bob", "Charlie"}; // 引用类型数组| 创建方式 | 示例代码 | 特点 |
|---|---|---|
| 声明后创建 | int[] arr; arr = new int[5]; | 逻辑清晰,分步骤 |
| 声明并创建 | int[] arr = new int[5]; | 一步完成,常用 |
| 声明并初始化 | int[] arr = {1, 2, 3}; | 直接初始化,方便简洁 |
| 匿名数组 | printArray(new int[]{1, 2, 3}); | 适合一次性使用 |
| 多维数组 | int[][] matrix = new int[3][4]; | 可灵活定义每行的列数 |
| 使用工具类 | Arrays.fill(arr, 42); | 简化填充、初始化操作 |
5. ArrayList 的常用方法
5.0 关键点:泛型
ArrayList 是一个泛型类,使用时可以通过 <E> 指定存储的数据类型。例如:
ArrayList<String>:只能存储字符串。ArrayList<Integer>:只能存储整数。ArrayList<Object>:可以存储任意对象。ArrayList<MyClass>:可以存储自定义类型。
ArrayList 是 Java 中最常用的动态数组类,它在 java.util 包中提供了许多便捷的方法,支持动态增长和减少。下面是常用的 ArrayList 方法及其详细讲解:
5.1 构造方法
ArrayList()创建一个初始容量为 10 的空列表。ArrayList<String> list = new ArrayList<>();ArrayList(int initialCapacity)创建一个指定初始容量的列表。ArrayList<String> list = new ArrayList<>(20);ArrayList(Collection<? extends E> c):创建一个包含指定集合的列表。List<String> initialList = Arrays.asList("A", "B", "C"); ArrayList<String> list = new ArrayList<>(initialList);
5.2 添加元素
add(E e):在列表末尾添加元素。list.add("Hello");add(int index, E element):在指定索引处插入元素,后续元素右移。list.add(1, "World");
5.3 获取元素
get(int index):返回指定索引处的元素。String element = list.get(0);
5.4 设置元素
set(int index, E element):替换指定索引处的元素。list.set(0, "New Value");
5.5 删除元素
remove(int index):删除指定索引的元素,并返回该元素。String removed = list.remove(1);remove(Object o):删除首次出现的指定对象,返回是否成功。boolean removed = list.remove("Hello");clear():清空列表。list.clear();
5.6 大小与空检查
size():返回列表中的元素数量。int size = list.size();isEmpty():检查列表是否为空。boolean isEmpty = list.isEmpty();
5.7 查询操作
contains(Object o):检查列表是否包含指定元素。boolean contains = list.contains("Hello");indexOf(Object o):返回首次出现的指定元素的索引,找不到返回-1。int index = list.indexOf("Hello");lastIndexOf(Object o):返回最后一次出现的指定元素的索引。int lastIndex = list.lastIndexOf("Hello");
5.8 批量操作
addAll(Collection<? extends E> c):将指定集合中的所有元素添加到列表末尾。list.addAll(Arrays.asList("A", "B", "C"));addAll(int index, Collection<? extends E> c):从指定位置开始插入集合中的元素。list.addAll(1, Arrays.asList("X", "Y"));removeAll(Collection<?> c):删除列表中所有与指定集合匹配的元素。list.removeAll(Arrays.asList("A", "B"));retainAll(Collection<?> c):仅保留与指定集合匹配的元素。list.retainAll(Arrays.asList("A", "B"));
5.9 转换操作
toArray():将列表转换为数组。Object[] array = list.toArray();toArray(T[] a):将列表转换为指定类型的数组。String[] array = list.toArray(new String[0]);
5.10 迭代与遍历
forEach(Consumer<? super E> action):对每个元素执行操作。list.forEach(System.out::println);iterator():返回列表的迭代器。Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); }
5.11 子列表
subList(int fromIndex, int toIndex):返回指定范围内的子列表(左闭右开)。List<String> subList = list.subList(1, 3);
5.12 排序
sort(Comparator<? super E> c):使用指定比较器对列表排序。list.sort(Comparator.naturalOrder());
5.13 克隆
clone():创建一个浅拷贝。ArrayList<String> clonedList = (ArrayList<String>) list.clone();
5.14 性能优化
ensureCapacity(int minCapacity):提前增加容量以避免频繁扩容。list.ensureCapacity(100);trimToSize():将容量调整为当前元素数量以节省内存。list.trimToSize();
5.15 使用场景
- 动态列表管理:如购物车、任务清单等。
- 批量操作:适用于需要频繁添加或删除元素的场景。
- 集合运算:如取交集、并集、差集。
通过了解和灵活使用 ArrayList 的这些方法,可以更高效地完成各种编程任务。
6. 优化寻找多个最大分数程序
import java.util.ArrayList;
public class ScoreArrayMaxScore {
public static void main(String[] args) {
// 声明六个变量,分别代表六门科目的成绩
int YuWenIndex = 0;
int ShuXueIndex = 1;
int WaiYuIndex = 2;
int WuLiIndex = 3;
int HuaXueIndex = 4;
int ShengWuIndex = 5;
// 每门课的名字
String[] names = new String[6];
names[YuWenIndex] = "语文";
names[ShuXueIndex] = "数学";
names[WaiYuIndex] = "外语";
names[WuLiIndex] = "物理";
names[HuaXueIndex] = "化学";
names[ShengWuIndex] = "生物";
// 每门课的成绩
double[] scores = new double[6];
// 用随机数给成绩赋值
for (int i = 0; i < 6; i++) {
scores[i] = 80 + Math.random() * 20;
}
// 找出最高分及其对应的科目
double maxScore = -1;
ArrayList<String> maxScoreSubjects = new ArrayList<>();
for (int i = 0; i < 6; i++) {
System.out.println(names[i] + "的成绩为" + scores[i]);
if (scores[i] > maxScore) {
// 如果找到更高的分数,更新最高分,并清空之前的科目记录
maxScore = scores[i];
maxScoreSubjects.clear();
maxScoreSubjects.add(names[i]);
} else if (scores[i] == maxScore) {
// 如果分数等于当前最高分,加入科目记录
maxScoreSubjects.add(names[i]);
}
}
// 输出结果
System.out.println("最高分为:" + maxScore);
System.out.println("取得最高分的科目有:" + maxScoreSubjects);
}
}7. 各种数据类型初始化数组元素默认类型
在 Java 中,数组被初始化时,其元素会被分配默认值。不同数据类型的默认值如下:
| 数据类型 | 默认值 |
|---|---|
byte | 0 |
short | 0 |
int | 0 |
long | 0L |
float | 0.0f |
double | 0.0 |
char | '\u0000' |
boolean | false |
Object (引用类型) | null |
示例代码:
public class DefaultArrayValues {
public static void main(String[] args) {
int[] intArray = new int[3];
double[] doubleArray = new double[3];
char[] charArray = new char[3];
boolean[] booleanArray = new boolean[3];
String[] stringArray = new String[3]; // String 是引用类型
// 打印默认值
System.out.println("int: " + intArray[0]); // 输出 0
System.out.println("double: " + doubleArray[0]); // 输出 0.0
System.out.println("char: '" + charArray[0] + "'"); // 输出空字符
System.out.println("boolean: " + booleanArray[0]); // 输出 false
System.out.println("String: " + stringArray[0]); // 输出 null
}
}欢迎关注我公众号:AI悦创,有更多更好玩的等你发现!
公众号:AI悦创【二维码】

AI悦创·编程一对一
AI悦创·推出辅导班啦,包括「Python 语言辅导班、C++ 辅导班、java 辅导班、算法/数据结构辅导班、少儿编程、pygame 游戏开发」,全部都是一对一教学:一对一辅导 + 一对一答疑 + 布置作业 + 项目实践等。当然,还有线下线上摄影课程、Photoshop、Premiere 一对一教学、QQ、微信在线,随时响应!微信:Jiabcdefh
C++ 信息奥赛题解,长期更新!长期招收一对一中小学信息奥赛集训,莆田、厦门地区有机会线下上门,其他地区线上。微信:Jiabcdefh
方法一:QQ
方法二:微信:Jiabcdefh

更新日志
1c35a-于aed17-于b999d-于df9a8-于3eeae-于7d682-于c5c1c-于eee30-于88572-于