My array is being loaded and is printing the cards out as planned (in the order they appear in the file). When I try to cycle back through the arraylist in a separate method to check whether or not the data is there, it only prints the last object rather than each of them. Can anybody tell me why?
The load method
public class
TestFrame {
//VARIABLES
private static Deck deck;
private static Card card;
private static Scanner scan;
private final static String fileName = "cards.txt";
static ArrayList<Card> cards = new ArrayList<>();
private static void Load(){
deck = new Deck();
card = new Card();
// Load in the card file so that we can work with the data from cards.txt internally rather than from the file constantly.
try(FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
Scanner infile = new Scanner(br)){
int numOfCards = infile.nextInt();
infile.nextLine(); // Do we need this? Yes we do. Illuminati confirmed.
for(int i=0; i < numOfCards; i++){
String value = infile.nextLine();
String suit = infile.nextLine();
Card newCard = new Card(value, suit);
card.addCard(newCard);
System.out.print(newCard.getValue());
System.out.print(newCard.getSuit());
System.out.println(" ");
//Print out the object before cycling through again so we can see if it's working
//We can use this to add then cards to the shuffle array at a later date
}
}
Which prints out this when ran:
ah
2h
3h
4h
5h
6h
7h
8h
etc etc. This is the order they're in the .txt file.
I then use these methods to display all of the cards to make sure I can manipulate the data elsewhere
private static void displayAllCards(){
Card[] cards = Card.getAll();
for(Card c : cards){
System.out.print(Card.getValue());
System.out.print(Card.getSuit());
System.out.println(" ");
}
}
and the getAll() method
public static Card[] getAll(){
Card[] brb = new Card[cards.size()];
int tempCount = -1;
for(Card c : cards){
tempCount++;
brb[tempCount] = c;
}
return brb;
}
When getAll()
is ran, it only prints out "ks" (king of spades) which is the last card in the .txt file. Can anybody tell me why this is happening?
Thanks
EDIT: CARD CLASS
package uk.ac.aber.dcs.cs12320.cards;
import java.util.ArrayList;
public class Card {
protected static String value;
protected static String suit;
static ArrayList<Card> cardsList = new ArrayList<>();
public Card(String v, String s){
this.value = v;
this.suit = s;
}
public Card() {
}
public static Card[] getAll(){
Card[] brb = new Card[cardsList.size()];
int tempCount = -1;
for(Card c : cardsList){
tempCount++;
brb[tempCount] = c;
}
return brb;
}
public static void deleteAll(){
cardsList.clear();
}
public static String getValue() {
return value;
}
public void setValue(String value) {
Deck.value = value;
}
public static String getSuit() {
return suit;
}
public void setSuit(String suit) {
Deck.suit = suit;
}
public void addCard(Card card){
cardsList.add(card);
}
}