我有这个数组练习。我想了解事情是如何运作的,如果有人可以的话
- 我们有一个名为
index
的 int 类型的对象数组,其中包含 4 个元素 - 我们有一个名为
islands
的字符串类型的对象数组,其中包含 4 个元素
我不明白事情是如何相互传递的,我需要一个很好的解释。
class Dog {
public static void main(String [] args) {
int [] index = new int[4];
index[0] = 1;
index[1] = 3;
index[2] = 0;
index[3] = 2;
String [] islands = new String[4];
islands[0] = "Bermuda";
islands[1] = "Fiji";
islands[2] = "Azores";
islands[3] = "Cozumel";
int y = 0;
int ref;
while (y < 4) {
ref = index[y];
System.out.print("island = ");
System.out.println(islands[ref]);
y ++;
}
}
拿一支笔和一张纸,做一个这样的表格,然后进行迭代:
y ref islands[ret]
--- --- ------------
0 1 Fiji
1 3 Cozumel
2 0 Bermuda
3 2 Azores
好吧,您已经在名为 index 的数组中添加了index
,然后在 while 循环中访问相同的值
int y=0;
ref = index[y]; // now ref = 1
islands[ref] // means islands[1] which returns the value `Fiji` that is stored in 1st position
首先,你创建一个保存int
s 的数组,数组的长度为 4(其中可以有 4 个变量):
int [] intArray = new int[4];
您的数组称为索引,这可能会混淆解释。数组的索引是您所指的"位置",介于0
和length-1
(含)之间。您可以通过两种方式使用它:
int myInt = intArray[0]; //get whatever is at index 0 and store it in myInt
intArray[0] = 4; //store the number 4 at index 0
下面的代码只不过是从第一个数组中获取一个数字并使用它来访问第二个数组中的变量。
ref = index[y];
System.out.println(islands[ref])
为了使其理解,拿一张纸和笔,以表格形式记下数组,然后循环访问以理解。(在学生时代,我们的老师称之为试运行)
首先我们表示数据
Iteration y ref ( `ref = index[y]`) islands
1 0 1 Fiji
2 1 3 Cozumel
3 2 0 Bermuda
4 3 2 Azores
因此,您可以进行迭代迭代 1
y=0
ref = index[y], i.e. index[0] i.e 1
System.out.print("island = "); prints island =
System.out.println(islands[ref]); islands[ref] i.e islands[1] i.e Fiji
因此,对于迭代 1,输出将是
island = Fiji