我这里有三个要求输入的类,应该在对话框中显示一个字符串数组。
第1课:
public class Card {
public int rank;
public int suit;
public String rankName;
public String suitName;
public String cardName;
public Card () {
rank = 0;
suit = 0;
rankName = "";
suitName = "";
cardName = "";
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public int getSuit() {
return suit;
}
public void setSuit(int suit) {
this.suit = suit;
}
public String getRankName() {
return rankName;
}
public void setRankName(String rankName) {
this.rankName = rankName;
}
public String getSuitName() {
return suitName;
}
public void setSuitName(String suitName) {
this.suitName = suitName;
}
public String getCardName() {
return cardName;
}
public void setCardName(String cardName) {
this.cardName = cardName;
}
}
Class 2 - 这是我应该输出存储在数组中的字符串的类。我认为我在正确的轨道上做泛型部分,但我不喜欢那样。请指导我打印所有这些。
import javax.swing.JOptionPane;
public class Deck {
public void assignIntegerValues(Card card) {
//Card card = new Card();
String[] suitNameArray = {"Clubs", "Spades", "Hearts", "Diamonds"};
String[] rankNameArray = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
List<Card> cardName = new ArrayList();
card.setSuitName (suitNameArray[card.getSuit()-1]);
card.setRankName (rankNameArray[card.getRank()-1]);
card.setCardName (card.getSuitName() + "-" + card.getRankName());
JOptionPane.showMessageDialog(null, card.cardName);
}
public void displayAll (Card card) {
for (int i=0; i<card.cardName.length(); i++) {
String print = JOptionPane.showMessageDialog(null, card.cardName[i]);
}
}
}
第3课:
import javax.swing.JOptionPane;
public class DisplayDeck {
public static void main(String[] args) {
Card card = new Card();
Deck deck = new Deck();
int answer;
String again;
do {
String suitString = JOptionPane.showInputDialog("Suit: ");
card.setSuit (Integer.parseInt(suitString));
String rankString = JOptionPane.showInputDialog("Rank: ");
card.setRank (Integer.parseInt(rankString));
deck.assignIntegerValues(card);
String answerString = JOptionPane.showInputDialog("Try again? (1/0) ");
answer = Integer.parseInt(answerString);
} while (answer == 1);
deck.displayAll(card);
}
}
我正在尝试显示用户输入的cardNames。
答案 0 :(得分:3)
public void displayAll (Card[] cards) {
String output = "";
for (int i=0; i<cards.length(); i++) {
output += cards[i].getCardName() + "\n";
}
JOptionPane.showMessageDialog(null, output);
}
你需要一个传递给displayAll的数组,否则你只需要一张卡。
然后在实际创建JOptionPane之前构建输出字符串。
答案 1 :(得分:1)
另一种方法取决于Deck
有一个集合,每个新的Card
都添加到其中:
class Deck {
private List<Card> cards = new ArrayList<Card>();
...
}
Card
覆盖toString()
,
@Override
public String toString() {
return cardName;
}
然后displayAll()
变得非常简单:
public void displayAll() {
JOptionPane.showMessageDialog(null,
new JScrollPane(new JList(cards.toArray())));
}