在 ArrayList 类中使用“get”方法时遇到问题。
Main 方法应该在 ArrayList 中创建一副纸牌,然后显示所有纸牌。我只是在寻找关于为什么在我的主要方法(游戏类)中出现“d.get(i)”错误的解释。如果我在甲板类中使用它,它工作正常。
游戏类:
package game;
import java.util.*;
public class Game {
public static void main(String[] args) {
/*Card f = new Card(2,7);
System.out.println(f.toString());*/
Deck d = new Deck();
int i = 0;
while(i < 52)
{
//where error occurs:
Card k = d.get(i);//get is underlined red
System.out.println(d.toString());
i++;
}
}
}
卡片类:
package game;
public class Card {
private int suit, value;
private String[] cardSuit = {"Spades", "Diamonds", "Hearts", "Clubs"};
private String[] cardValue = {"Ace", "King", "Queen", "Jack", "10",
"9", "8", "7", "6", "5", "4", "3", "2"};
public Card(int cSuit, int cValue)
{
suit = cSuit;
value = cValue;
}
public String toString()
{
String cardInfo = cardValue[value] + " of " + cardSuit[suit];
return cardInfo;
}
public int getValue()
{
return value;
}
public int getSuit()
{
return suit;
}
}
甲板类:
package game;
import java.util.*;
public class Deck {
private ArrayList<Card> deck;
public Deck(){
deck = new ArrayList<>();
for(int i = 0;i<4;i++){
for(int j = 0;j<13;j++){
deck.add(new Card(i,j));
}
}
}
}
最佳答案
您可以在 Deck
类中为 ArrayList
实现一个 getter,或者向 Deck
类添加一个 get 方法并委托(delegate)给数组列表
:
public Card get(int index) {
return this.deck.get(index);
}
关于java - ArrayList get 方法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36463389/