2012-12-22 147 views
1

我有这个数组练习。我想知道是如何工作的,如果有人能Java Array练习

  1. 我们有一个int类型的对象数组称为index有4个元素
  2. 我们有类型的对象数组字符串称为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 ++; 
    } 
    } 
+3

你的“具体”问题是什么? –

+2

考虑使用for循环来代替while循环(int y = 0; y <4; y ++)。只是一个更好的风格。无论如何,你的问题是什么! – SIGKILL

+0

另请注意,“家庭作业”标记已被正式弃用 –

回答

6

拿一支笔和纸,让这样的一个表,并办理迭代:

y ref islands[ret] 
--- --- ------------ 
0  1  Fiji 
1  3  Cozumel 
2  0  Bermuda 
3  2  Azores 
+0

+1清除映射。 – vels4j

0

嗯,你已经加入数组指定索引,然后在访问相同的值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 
0

首先,使保持int秒的阵列,所述阵列具有长度4(4个变量可以在它):

int [] intArray = new int[4]; 

你的数组被称为索引,这可能是混淆的解释。阵列的索引是您所指的“位置”,位于0length-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]) 
0

为了使它理解,拿一纸和笔,并以表格形式记下数组,并循环遍历循环来理解。 (早在学生时代,我们的老师(S)将其称为干运行)

首先我们代表的是数据

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