gpt4 book ai didi

java - 如何调用另一个类的方法?

转载 作者:行者123 更新时间:2023-11-30 06:41:54 24 4
gpt4 key购买 nike

所以我是 OOP 的菜鸟,目前我在使用另一种方法的函数时遇到问题。下面的类是纸牌游戏的主要类。在这里,它通过从 Game 类创建一个对象来创建一副纸牌。然后它会使用创建的牌组开始游戏,并打印出牌组的大小。

public class Run {

public static void main(String[] args) {

Game game;
System.out.println("Welcome!");
play = true;
while (play) {
game = new Game(3); //Create deck of card based on number of ranks given
game.play(); //Starts the game with deck of card
}

}

下面的类是游戏类。当游戏开始时,它应该打印出所创建的牌组的大小。

public class Game {
public Game(int ranks)
{
Deck Main = new Deck(ranks);
}
public static void play()
{
System.out.println(Main.size()); //Where the error occurs
}

下面的类是 Deck 类,它实际创建牌组并有一个返回牌组大小的方法。

public class Deck {

private ArrayList<Card> cards;

public Deck(int range) {
cards = new ArrayList<Card>();
for (int i=1; i<=range; i++)
{
Card card = new Card(1, i);
Card card2 = new Card(2, i);
Card card3 = new Card(3, i);
Card card4 = new Card(4, i);
cards.add(card);
cards.add(card2);
cards.add(card3);
cards.add(card4);
}
}
public int size()
{
int num=cards.size();
return num;
}

最后一个类是 Card 类。

public class Card {
private int rank;
private int suit;
public Card(int s, int r)
{
suit=s;
rank=r;
}
public int getSuit()
{
return suit;
}
public int getRank()
{
return rank;
}

由于我缺乏理解,这一定是一个明显的错误,所以任何人都可以说明如何修复它吗?

最佳答案

您在 Deck 类的构造函数中将“Main”声明为局部变量。这意味着它仅在该构造函数的主体中可见。

您需要将局部变量转换为类的字段。只有这样它才能在类(class)的其他地方变得“可见”!与您在卡类中为套件和排名所做的正确操作完全相同!

当然播放方法应该是静态的!一场比赛是关于一个套牌,而不是“所有套牌”!

关于java - 如何调用另一个类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54413774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com