Java 一个对象如何从另一个类中创建的对象调用方法
我是Java新手(一般来说也是编程新手),我正试图编写一个可以玩围棋的程序,但是我很难让一个对象调用另一个对象的方法。它还没有完成,但这是我到目前为止所做的。 这将被调用以开始游戏:Java 一个对象如何从另一个类中创建的对象调用方法,java,object,Java,Object,我是Java新手(一般来说也是编程新手),我正试图编写一个可以玩围棋的程序,但是我很难让一个对象调用另一个对象的方法。它还没有完成,但这是我到目前为止所做的。 这将被调用以开始游戏: public class StartGame { public static void start(){ Deck deck = new Deck(1); GoFishHumanPlayer player = new GoFishHumanPlayer(); GoFishAiPlayer
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{
私有整数[]手=新整数[14];
私有整数对;
公营部门{
对于(int x=0;x<5;x++){
int y=deck.draw();//在这里我得到一个错误“deck无法解析”
手[y]++;}
}
}
在GoFishPlayer的第8行,我的IDE显示“无法解析甲板”。回到StartGame,我创建了一个名为deck的对象,但如何使所有类都可以访问它。无需使所有类都可以访问它,只需在
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();
}
}
无需使所有类都可以访问它,只需在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();
}
}
如果需要所有类都可以访问它,只需将其传递给构造函数即可
public class GoFishPlayer {
private Deck deck;
public GoFishPlayer(Deck deck) { this.deck = deck; }
...
}
如果需要所有类都可以访问它,只需将其传递给构造函数即可
public class GoFishPlayer {
private Deck deck;
public GoFishPlayer(Deck deck) { this.deck = deck; }
...
}
您必须为玩家实例提供对牌组
实例的引用。为什么您不能在GoFishPlayer类中创建牌组对象您必须为玩家实例提供对牌组
实例的引用。为什么您不能在GoFishPlayer类中创建牌组对象