use*_*291 -1 java arrays loops object
public enum Suit
{
CLUBS,
HEARTS,
SPADES,
DIAMONDS
}
public enum Value
{
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
JACK,
QUEEN,
KING,
ACE
}
Run Code Online (Sandbox Code Playgroud)
Card.java
public class Card {
private Suit suit;
private Value value;
public Card(Suit theSuit, Value theValue)
{
suit = theSuit;
value = theValue;
}
public String toString()
{
return value + " of " + suit;
}
public Value getValue()
{
return value;
}
public Suit getSuit()
{
return suit;
}
public boolean equals(Card other)
{
if (value.ordinal() == other.value.ordinal()
|| suit.ordinal() == other.suit.ordinal())
{
return true;
}
else {
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
CardPile.java
public class CardPile
{
public Card[] cards;
private int numCards;
public CardPile()
{
this.cards = new Card[52];
this.numCards = 0;
// The problem is here, when I try to iterate through the enums and the
// array to populate my cards[] of 52 objects Card it populates it with
// 52 Card which are all ACE of DIAMONDS, it looks like the triple loops
// populates 52 times the two last elements of my enum, but I can't
// figure out how to fix that! Thanks in advance!
for (Suit s : Suit.values())
{
for (Value v : Value.values())
{
for (int ? = 0; ? < cards.length; ?++)
{
cards[?] = new Card(s, v);
}
}
}
}
public boolean isEmpty()
{
for (int i = 0; i < cards.length; i++)
{
if (cards[i] != null)
{
return false;
}
}
return true;
}
public int getNumCards()
{
return numCards;
}
}
Run Code Online (Sandbox Code Playgroud)
问题出在这里:
for (int ? = 0; ? < cards.length; ?++) {
cards[?] = new Card(s, v);
}
Run Code Online (Sandbox Code Playgroud)
您使用相同的s和v变量来创建Card实例并将其分配给cards数组中的所有元素,替换每个(s,v)对组合上的每个值.
更改代码以便仅使用前2 for-loop秒填充它:
int count = 0;
for (Suit s : Suit.values()) {
for (Value v : Value.values()) {
if (count < cards.length) {
cards[count++] = new Card(s, v);
}
}
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,你不应该使用名称作为?变量,并确保缩进你的代码.
| 归档时间: |
|
| 查看次数: |
2187 次 |
| 最近记录: |