2014-01-16 43 views
1

我正在研究Java中Array問題的一些練習。我知道當你聲明一個對象時,你可以把它放在一個向右或向左移動的數組中。但是,無論如何,您可以隨意將它移動到左側還是右側?左移或右移陣列表中的對象隨機

在這種做法中,我將數組大小設置爲100.我想檢查單元格是否爲空。如果不是空的,則物體(熊和魚)向左或向右(隨機)移動。如果它是空的,它會做別的事情。

 For example: 
    //Create an Array 
    //Add objects into array 
     Animal[] river = new Animal[100]; 
     Fish f = new Fish(); 
     Bear b = new Bear(); 
     river[0]= f; 
     river[1]= b; 

      for (int i = 0; i<river.length; i++){ 
        if (river[i] != null){ 
     //not sure how to shift byte right and left 
     } 

任何想法?幫助將不勝感激。

謝謝

+0

不要混淆,'ArrayList的= Array' – Christian

+0

謝謝您的回覆!我知道我正在研究一個Array。我不知道如何實施移位方法 –

+0

有一個問題,您爲什麼想要這樣做?目的是什麼? – Christian

回答

2

您的想法太籠統。向左或向右移動實際上是將其從當前位置移開並添加到另一個位置。

,爲您帶來僞代碼是這樣的:

if position is occupied 
    store animal on position in variable 
    empty the position 
    put animal from variable in another position 

而最後一步取決於你繞圈。你可以做position + 1position - 1,或者你可以使用Random類實際使用一個隨機點。

0

通過左右「移位」,聽起來像是您想要將river陣列中的某個項目與其相鄰的項目隨機交換。正如其他人所提到的,您可以使用Random類生成隨機值。

我將生成{-1, 0, 1}之一:如果編號爲0,則該項不會移動;如果號碼爲-1,則將當前項目(river[i])與其左側鄰居(river[i-1])交換;如果號碼爲1,則將當前項目(river[i])與其右側鄰居(river[i+1])交換。一定要實施swap方法,並小心不要超出數組的界限。


編輯:

Random rnd = new Random(); 
for (int i=0; i<river.length; i++) 
{ 
    int shift = rnd.nextInt(3) - 1; // -1, 0, or 1 

    switch(shift) 
    { 
     case -1: // swap to the left 
      if (i > 0) 
       swap(river, i, i-1); 
      break; 

     case 1: // swap to the right 
      if (i < river.length-1) 
       swap(river, i, i+1); 
      break; 

     default: 
      // no shift 
    } 
} 
+0

感謝您的評論。所以你會建議這樣的事情? for(int i = 0; i

+0

@HinWong我編輯了代碼來說明我的觀點 – mdl