此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
一个盒子里装很多值
- 一个数组(array)按顺序保存很多个相同类型的值。
- 在此之前,一个变量只保存一个值。数组保存一整个列表。
- 例如,一个班的考试分数可以放在一个
int数组里。
用值来创建数组
- 如果你知道这些值,就把它们列在花括号
{ }里。 - 类型是元素类型再加
[],比如int[]。 - Java 会数你给了多少个值,并创建对应大小的数组。
English
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
System.out.println(scores[0]); // 90
System.out.println(scores[2]); // 70
}
}
下标位置
- 每个值都有一个下标(index,它的位置)。下标从 0 开始。
- 所以第一个值是
scores[0],第二个是scores[1],以此类推。 - 你也可以修改一个值:
scores[1] = 85;。
English
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
scores[1] = 85; // change the middle value
System.out.println(scores[1]); // 85
}
}
创建一个空数组
- 用
new int[n]来创建一个有n个值的数组。 - 每个
int位置都会自动从 0 开始。 - 然后你一个一个地填进去。
English
public class Main {
public static void main(String[] args) {
int[] nums = new int[3]; // {0, 0, 0}
nums[0] = 5;
nums[1] = 6;
System.out.println(nums[0] + " " + nums[1] + " " + nums[2]); // 5 6 0
}
}
.length
array.length告诉你数组里有多少个值。- 注意:没有圆括号 —— 是
scores.length,不是scores.length()。 - 最后一个有效下标永远是
length - 1。
English
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
System.out.println(scores.length); // 3
System.out.println(scores[scores.length - 1]); // 70 (last value)
}
}
用 for 循环遍历
- 要访问每个值,就让下标从
0循环到length - 1。 - 用
i < array.length作为停止条件。 - 下面我们把每个值加起来。
English
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
int total = 0;
for (int i = 0; i < scores.length; i++) {
total = total + scores[i];
}
System.out.println(total); // 240
}
}
增强 for 循环
- 增强 for(也叫 “for-each”)直接访问每一个值。
- 将其读作:“遍历
scores中的每个int v”。 - 当你只需要值、不需要下标时,就用它。
English
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
int total = 0;
for (int v : scores) {
total = total + v;
}
System.out.println(total); // 240
}
}
常见错误
a.length不带();合法下标是0到a.length - 1。- 越界会抛出 ArrayIndexOutOfBoundsException。
现在轮到你
- 有些任务打印一个结果;有些任务要补全一个由 Harness 调用的方法。
- 记住:下标从 0 开始,最后一个下标是
length - 1。 - 对于完整程序,Run(运行)会编译并执行它。对于方法或类任务,Check answer(检查答案)会使用提供的测试编译您的代码并显示结果。
探索
A 1-D array, indexed
An array stores values in order; reach one with a[i].
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
The array nums is already filled. Use a loop to add up all its values and print the total on one line. For {4, 8, 15, 16, 23, 42} the output is 108.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Complete sum(int[] a) so it returns the sum of all values in the array. An empty array should return 0. The checker calls it with several arrays.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Complete doubleAll(int[] a). It does not return anything. Instead it changes the array in place so every value becomes twice as big. {1, 2, 3} becomes {2, 4, 6}.
点击“运行”查看此处输出。