正在加载我的阵列,并按计划打印出卡片(按照它们出现在文件中的顺序).当我尝试以单独的方法循环回到arraylist以检查数据是否存在时,它只打印最后一个对象而不是每个对象.谁能告诉我为什么?
加载方法
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
}
}
Run Code Online (Sandbox Code Playgroud)
运行时打印出来的是:
ah
2h
3h
4h
5h
6h
7h
8h
Run Code Online (Sandbox Code Playgroud)
等等.这是他们在.txt文件中的顺序.
然后我使用这些方法显示所有卡片,以确保我可以在其他地方操纵数据
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(" ");
}
}
Run Code Online (Sandbox Code Playgroud)
和getAll()方法
public static Card[] getAll(){
Card[] brb = new Card[cards.size()];
int tempCount = -1;
for(Card c : cards){
tempCount++;
brb[tempCount] = c;
}
return brb;
}
Run Code Online (Sandbox Code Playgroud)
当getAll()运行时,它只打印出"ks"(黑桃之王),这是.txt文件中的最后一张卡.任何人都可以告诉我为什么会这样吗?
谢谢
编辑:卡片类
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);
}
Run Code Online (Sandbox Code Playgroud)
}
小智 6
card.addCard(newCard);
Run Code Online (Sandbox Code Playgroud)
我想这应该是cards.addCard(newCard);代替