How to call method from another class?

A. Sri :

So I'm a rookie at OOP and I am currently having trouble using a function from another method. The class below is the main class for a card game. Here it creates a deck of cards by creating an object from the Game class. It then starts the game with the created deck and should print the size of the deck.

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
    }

}

The class below is the Game class. When the game starts it should print the size of the deck created.

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
}

The class below is the Deck class where it actually creates the deck and has a method that returns the size of that 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;
}

The final class is the Card class.

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;
}

It must be an obvious error due to my lack of understanding so can anyone show what to do to fix it?

GhostCat salutes Monica C. :

You declared "Main" as a local variable inside the constructor of the Deck class. That means it is only visible in the body of that constructor.

You need to turn the local variable into a field of your class instead. Only then it becomes "visible" in other places of your class! The very same thing you did correctly for suite and rank in your Card class!

And of course the play method should not be static! A game is about one deck, not "all of them"!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=131026&siteId=1