2013-08-02 47 views
1

我是新來的Java(和一般編程),我試圖編寫一個程序來玩Go Fish,但我有一個很難得到一個對象來調用另一個對象的方法。它還沒有完成,但這是我迄今爲止所做的。 這將被要求開始遊戲:一個對象怎樣才能從另一個類創建的對象中調用方法

public class StartGame { 

public static void start(){ 
    Deck deck = new Deck(1); 
    GoFishHumanPlayer player = new GoFishHumanPlayer(); 
    GoFishAiPlayer ai = new GoFishAiPlayer(); 
    player.drawHand(); 
    ai.drawHand(); 
    player.turn(); 
} 
} 

一個對象,它的功能作爲遊戲平臺。

import java.util.Random; 

public class Deck { 

private int[] card = new int[14]; 
private int size; 

Random r = new Random(); 

public Deck(int x){ 
    size = x; 
    card[0] = 4 * size * 13; 
    card[1] = 4 * size; 
    card[2] = 4 * size; 
    card[3] = 4 * size; 
    card[4] = 4 * size; 
    card[5] = 4 * size; 
    card[6] = 4 * size; 
    card[7] = 4 * size; 
    card[8] = 4 * size; 
    card[9] = 4 * size; 
    card[10] = 4 * size; 
    card[11] = 4 * size; 
    card[12] = 4 * size; 
    card[13] = 4 * size;} 

public int draw(){ 
    int x = r.nextInt(card[0]) + 1; 
    int y = 1; 
    while(x>card[y]){ 
     x -=card[y]; 
     y++;} 
    card[y]--; 
    card[0]--; 
    return y;} 

} 

下一課將由GoFishHumanPlayer和GoFishAiPlayer擴展。這些對象將代表球員。

public class GoFishPlayer { 

private int[] hand = new int[14]; 
private int pairs; 

public void drawHand(){ 
    for(int x = 0; x < 5; x++){ 
     int y = deck.draw();//Here's where I get an error "deck cannot be resolved" 
     hand[y]++;} 
} 
} 

在GoFishPlayer的8行我的IDE說 「甲板不能得到解決」。回到StartGame中,我創建了一個名爲deck的對象,但是如何讓所有類都可以訪問它。

+0

您必須對您的播放器實例提供'Deck'實例的引用。 –

+0

爲什麼你不能在你的GoFishPlayer類中創建一個deck對象 –

回答

4

沒有必要讓所有的類都可以訪問,只是在GoFishPlayer構造函數傳遞引用:

public class GoFishPlayer { 
    private Deck deck; 

    public GoFishPlayer(Deck deck) { this.deck = deck; } 
    ... 
} 

public class StartGame { 
    public static void start(){ 
    Deck deck = new Deck(1); 
    GoFishHumanPlayer player = new GoFishHumanPlayer(deck); 
    GoFishAiPlayer ai = new GoFishAiPlayer(deck); 
    player.drawHand(); 
    ai.drawHand(); 
    player.turn(); 
    } 
} 
1

只需將它傳遞給構造函數,如果ü需要它是所有類訪問。

public class GoFishPlayer { 
private Deck deck; 

public GoFishPlayer(Deck deck) { this.deck = deck; } 
... 
} 
相關問題