在通过方法调用创建的数组中打印位置0

时间:2018-06-20 18:39:26

标签: java

我正在尝试使用两个单独的类来创建卡片组,这两个类将调用createCard方法并将此卡片返回并将其附加到我的DeckOfCards类中的数组中。就我正在学习的数组而言,这似乎是一次冒险。截至目前,我当前的问题是试图找出为什么当我请求打印附录0时收到错误的卡位置。因此,如果我输入2 NumberOfRanks和2 NumberOfSuits并尝试打印出位置0,我将收到第二个位置。如果我尝试使用3&3打印出来,我将获得第三名。

抱歉,该文本块。

有什么想法吗?

public class DeckofCards {
    private int NumberOfRanks;
    private int NumberOfSuits;
    private int SizeOfDeck;
    private int whatSuit;

    public void DeckofCards ( int NumberOfRanks, int NumberOfSuits ) {
        this.NumberOfRanks = NumberOfRanks;
        this.NumberOfSuits = NumberOfSuits;

        SizeOfDeck = NumberOfRanks * NumberOfSuits;

        Cards newCard = new Cards();

        newCard.setCards ( NumberOfRanks, NumberOfSuits );

        String[] newDeck = new String [ SizeOfDeck ];
        int counter;
        for ( counter=0; counter <= NumberOfRanks; counter++ ) {

        for ( whatSuit = 1; whatSuit <= NumberOfSuits; whatSuit++ ){
            newCard.createCard ( counter, whatSuit );
            newDeck[counter] = newCard.createCard ( counter, whatSuit );
            System.out.println ( newDeck[ counter ] );
        }

    }
   System.out.println ( newDeck [0] );
}


public String createCard( int newCard, int whatSuit ) {


    createCard = newCard;
    theNumber = Integer.toString(createCard + 1);
    theSuit = Integer.toString ( whatSuit );

    theCard = ( "S" + theSuit + "R" + theNumber );

    return theCard;

}



Output:

How many suits? 2
How many ranks? 2 
S1R1
S2R1
S1R2
S2R2
S1R3
S2R3
S2R1 //Attempt to print position 0

Output:
How many suits? 3
How many ranks? 2
S1R1
S2R1
S3R1
S1R2
S2R2
S3R2
S1R3
S2R3
S3R3
S3R1 //Attempt to print position 0

1 个答案:

答案 0 :(得分:5)

问题是您不是每次都添加counter来添加卡,而是每个完整的内部循环只添加一次。通过重复使用相同的索引,您将覆盖数组中的值。

更改外部循环以遍历rank,并使用类似以下内容:

int counter = 0;
for (int rank = 1; rank <= NumberOfRanks; rank++) {
    for (whatSuit = 1; whatSuit <= NumberOfSuits; whatSuit++) {
        newDeck[counter++] = newCard.createCard(rank, whatSuit);
        System.out.println(newDeck[counter - 1]);
    }
} 

优良作法是最小化变量的范围,因此请删除whatSuit作为实例字段并使其成为循环变量,即for (int whatSuit; ...)