anvd
anvd

Reputation: 4047

invoke void method

I need to invoke a void method before call another method.

I have this method

    public void shuffle() {
    various = new Random();

    currentCard = 0;
    currentTotal1 = 0;
    currentTotal2 = 0;

    for (int first = 0; first < deckOfCards.length; first++) {
        int second = various.nextInt(number_cards);

        Card temp = deckOfCards[first];
        deckOfCards[first] = deckOfCards[second];
        deckOfCards[second] = temp;
    }
}

And in another class I have:

public class GameRules {
final deck myDeckOfCards = new deck();
myDeckOfCards.shuffle(); //error here

// first
public ImageIcon GameRules1() {
    return myDeckOfCards.giveCardPlayer1().getImage();
}

The basic problem is that I need to do shuffle in the deck of cards before show a card. Without shuffle method the order of cards is sequential

Any idea? If I put the method inside public ImageIcon GameRules1() doesn't give error, but I need shuffle all cards before game, no before each give card method.

thanks

Upvotes: 1

Views: 2964

Answers (3)

Sergei Tachenov
Sergei Tachenov

Reputation: 24919

Either use a constructor as suggested, or, if at some point you have multiple constructors, you may wish to move the code that is common to them to an initializer:

public class GameRules {
final deck myDeckOfCards = new deck();

// instance initalizer
{
  myDeckOfCards.shuffle(); // no more error
}

But, as pointed out in the comments, using a constructor is better, chaining constructors if necessary. It turns out that instance initializers are best used in anonymous classes.

Upvotes: 5

jjnguy
jjnguy

Reputation: 138982

You should place that call inside your constructor for the class:

public GameRules() {
    myDeckOfCards.shuffle();
}

The constructor is the place where you do initialization tasks for your objects.

Also, you really shouldn't have a method called GameRules() that returns an ImageIcon. You should rename that method getImage or something like that. Then, when you create a GameRules with the consturctor and call getImage on it, the deck will be shuffled.

Example:

GameRules gr = new GameRules(); // deck gets shuffled in constructor call
JLabel test2 = new JLabel(gr.getImage());

Check out the Java tutorials for a good tutorial on writing constructors for your classes.

Upvotes: 8

Benoit Thiery
Benoit Thiery

Reputation: 6387

Why don't you call shuffle method in deck constructor directly?

Upvotes: 2

Related Questions