我正在努力使Java更精通。我正在制作一个简单的纸牌游戏来测试我的基本技能。我在Deck课上遇到过一个问题。 for循环不会在我的arraylist中创建新的卡片对象,即使它们应该。当我调用getTotalCards时,arraylist的大小始终为0.任何关于我做错的想法?
主类:
package gameofcards;
import java.util.Random;
import static gameofcards.Card.*;
public class GameOfCards {
public static void main(String[] args) {
Deck d1 = new Deck();
System.out.println(d1.getTotalCards());
}
}
甲板课程:
package gameofcards;
import java.util.ArrayList;
public class Deck {
private ArrayList<Card> cards;
public Deck(){
cards = new ArrayList<Card>();
for(int i = 1; i >=4; i++){
for(int j = 1; j >=13; j++){
cards.add(new Card(i,j));
}
}
}
public int getTotalCards(){
return cards.size();
}
}
卡类:
package gameofcards;
public class Card {
private int Suite;
private int Rank;
public static final int Club = 1;
public static final int Diamond = 2;
public static final int Hearts = 3;
public static final int Spade = 4;
public static final int Jack = 10;
public static final int Queen = 11;
public static final int King = 12;
public static final int Ace = 13;
public void setSuite(int cardSuite){
Suite=cardSuite;
}
public int getSuite(){
return Suite;
}
public void setRank(int cardRank){
Rank=cardRank;
}
public int getRank(){
return Rank;
}
public Card(int Suite, int Rank){
this.Suite = Suite;
this.Rank = Rank;
}
public String cardSuite(){
switch(Suite){
case Club: return "Clubs";
case Diamond: return "Diamonds";
case Hearts: return "Hearts";
case Spade: return "Spades";
default: return "Joker";
}
}
public String cardRank() {
switch(Rank){
case 2: return "2";
case 3: return "3";
case 4: return "4";
case 5: return "5";
case 6: return "6";
case 7: return "7";
case 8: return "8";
case 9: return "9";
case 10: return "Jack";
case 11: return "Queen";
case 12: return "King";
case 13: return "Ace";
default: return "Joker";
}
}
}
答案 0 :(得分:2)
for循环中的条件错误。应该是i <= 4且j <= 13
for(int i = 1; i <=4; i++){
for(int j = 1; j <=13; j++){
cards.add(new Card(i,j));
}
}
答案 1 :(得分:2)
您的循环条件错误。
而不是:
for(int i = 1; i >=4; i++){
应该是:
for(int i = 1; i <=4; i++){
与内循环条件类似的问题。
您希望在i
小于或等于4时循环。
它没有添加卡片,因为它从未首先进入循环。
解决这个问题的一个简单方法就是在循环中放置一个println
,看看会发生什么。你会注意到它从未打印过。