package com.test.game;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class Card {
private static String[] colours = new String[]{"E", "L", "H", "S"};
private static String[] cardValues = new String[]{"7", "8", "9", "10", "B", "D", "K", "A"};
private String cardValue;
private String colour;
private Card(String cardValue, String colour) {
this.cardValue = cardValue;
this.colour = colour;
}
public String toString() {
return cardValue colour;
}
static void CardDeck() {
ArrayList<Card> cards = new ArrayList<Card>();
for (int i = 0; i < colours.length; i ) {
for (int j = 0; j < cardValues.length; j ) {
cards.add(new Card(cardValues[j], colours[i]));
}
}
System.out.println(cards);
}
static void Collections(ArrayList<Card> cards, int seed){
Collections.shuffle(cards, new Random(seed));
System.out.println(cards);
}
public static void main(String[] args) {
System.out.println();
}
}
package com.test.game;
import java.util.ArrayList;
import java.util.Random;
public class Game {
public static void main(String[] args) {
Card.CardDeck();
Card.Collections();
}
}
So I am working on a card game right now. The first class creates an array list containing cards with the help of the method CardDeck()
this method gets called in the Game class and that works perfectly fine. Now in the Method Collections() this array list is supposed to be shuffled. So that the cards are in a random order.
Therefore I have 2 questions. First is the way I am shuffling the cards right? And how can I call this Collectinons()
method in another class? Due to the fact that it has parameters it does not work. I have found some similar questions but they did not really work for me. (creating a new instance)
Can someone help?
CodePudding user response:
Instead of printing the list in CardDeck
(that you should rename to cardDeck
), just return the deck, so that the caller can use it:
static List<Card> cardDeck() {
ArrayList<Card> cards = new ArrayList<Card>();
for (int i = 0; i < colours.length; i ) {
for (int j = 0; j < cardValues.length; j ) {
cards.add(new Card(cardValues[j], colours[i]));
}
}
return cards;
}
You can then pass it to your method Collections
(that you should rename to shuffle
):
static void shuffle(List<Card> cards, int seed){
Collections.shuffle(cards, new Random(seed));
}
And don't print it there: the caller can always print it afterwards.
Your main
method becomes:
public static void main(String[] args) {
List<Card> deck = Card.cardDeck();
Card.shuffle(deck, whatever);
System.out.println(deck);
}