2012-12-22 144 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