S
S
syntax2013-11-04 19:43:43
Java
syntax, 2013-11-04 19:43:43

How to get different elements of the same array for different class objects?

Greetings. There is an array String[] in which there are 32 elements (cards). There is a Players class. It is necessary to write a getCards method so that when Players p1.getCards is called, each of the players (p1,p2,p3,p4) receives 8 different array elements in a row (p1 receives the first 8 elements, p2 the next 8). Suggest an idea how to organize the getCards method? I'm new to java and I'm not sure the best option would be to use an array. It is possible that it will be more beautiful / more efficient to use a collection. Thank you!

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Dmitry Kharitonov, 2013-11-04
@syntax

PlayerStore the index (0, 1, 2, 3) of the player in the class playerIdx.
The method getCardsis something like:

String[] getCards() {
    String[] ret = new String[8];

    int l = playerIdx * 8;
    int r = l + 8;
    for (int i = l, j = 0; i < r; i++, j++)
        ret[j] = cards[i]; 

    return ret;
}

If instead of a string array there is ArrayList, then it will be possible in one line using the subList().

X
xanep, 2013-11-04
@xanep

Obviously you need to use a queue for the deck of cards instead of an array.
I myself am not familiar with Java, so I won’t suggest specific classes / methods.

@
@xave, 2013-11-04
_

I didn’t understand a bit, p1 is an instance of the Players class, so its .getCards() method is not static, but at the same time it performs the same action for any instance of this class (that is, it does not depend on the instance), but means it is logical to declare it static.
Let's say you have it static. Then it is logical to store the list of players (instances of the Players class) inside the Players class itself, prohibit the instance from it through new, making the constructor private and use the getInstance() static method to create instances, when accessing which the list of players inside the Players class would be updated.
Next you have your Players.getCards(String[] cards) method, also static. There is no problem in iterating through the list of players in this class and giving each a chunk of the cards array via System.arrayCopy(). You can store cards in an ArrayList, not in an array, until the concept of the program is visible, to say which is more appropriate.

V
Volodymyr S., 2013-11-06
@VYBGSS

Yes, it can be different. It is also possible to rivet a static SortCards in a separate static Game class, which will pass the necessary cards to the Players instances, only then getCards will not be without parameters.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question