2016-11-20 85 views
1

我想了一小掃雷遊戲代碼中的一些基本的東西,我們在大學做。現在我的問題是我的代碼。return new int [] {randomHeight,randomWidth};

public class Minesweeper1 { 

    public static int[][] makeRandomBoard(int s, int z, int n){ 
     //creating the field and fill with 0 
     int feld[][] = new int [s][z]; 
     for(int i = 0; i < s; i++){ 
      for(int j = 0; j < z; j++){ 
       feld[i][j] = 0; 
      } 
     } 

     //n-times to fill the field 
     for(int i = 0; i < n; i++){ 
      selectRandomPosition(s, z); 
      //want to get them from selectRandomPosition 
      feld[randomHeight][randomWidth] = 1; 
     } 
    } 
} 

所以開始selectRandomPosition代碼:

public static int[] selectRandomPosition(int maxWidth, int maxHeight) { 
    int randomHeight = StdRandom.uniform(0, maxHeight); 
    int randomWidth = StdRandom.uniform(0, maxWidth); 
    return new int[]{randomHeight, randomWidth}; 
} 

在這裏,我不能改變什麼,但它返回一個新的數組。現在是我的問題,我該如何使用新的陣列我makeRandomBoard方法,因爲我不知道數組的任何名稱。當我使用feld[randomHeight][randomWidth] = 1;,它說,它不知道這些變量。

+1

的可能的複製[如何存儲由Java中的方法返回一個數組(http://stackoverflow.com/questions/2378756/how-to-store-一個陣列退回逐一個-方法-在-java的) – BackSlash

+0

'randomHeight'和''randomWidth'功能selectRandomPosition'的局部變量。你不能在這個函數之外使用這些變量。 – McNets

+0

@mcNets我知道,但我的問題是我如何讓他們有沒有數組的名字,因爲我們並沒有在任何講座。 – FireCross

回答

1

如何在我的makeRandomBoard方法中使用新數組,因爲我不知道數組的任何名稱?

呼叫的方法,並且其返回值分配給一個變量。現在您對陣列的名稱:

// Make a call 
int[] randomArray = selectRandomPosition(maxW, maxH); 
// Access the width 
int randomW = randomArray[0]; 
// Access the height 
int randomH = randomArray[1]; 
+0

非常感謝,從來沒有這樣說過:D – FireCross

相關問題