我的甲板类遇到问题,我的代码创建了一个有限的牌组,并将从数组中返回一个值,然后将其设为null。它还会检查它是否为空,因为getCard()被多次调用。这确保没有重复的卡。问题是,当我运行我的代码时,它打印出空行,这必须意味着它返回null,这是我的理解发生的。
public class Deck {
public int randomNumber;
private String card;
private String [] deck;
public Deck()
{
deck = new String [] {"Ace Of Hearts" , "2 Of Hearts" , "3 Of Hearts" , "4 Of Hearts" , "5 Of Hearts" , "6 Of Hearts" , "7 Of Hearts" ,
"8 Of Hearts" , "9 Of Hearts" , "10 Of Hearts" , "Jack Of Hearts" , "Queen Of Hearts" , "King Of Hearts" ,
"Ace Of Diamonds" , "2 Of Diamonds" , "3 Of Diamonds" , "4 Of Diamonds" , "5 Of Diamonds" , "6 Of Diamonds" ,
"7 Of Diamonds" , "8 Of Diamonds" , "9 Of Diamonds" , "10 Of Diamonds" , "Jack Of Diamonds" , "Queen Of Diamonds" ,
"King Of Diamonds" , "Ace Of Clovers" , "2 Of Clovers" , "3 Of Clovers" , "4 Of Clovers" , "5 Of Clovers" ,
"6 Of Clovers" , "7 Of Clovers" , "8 Of Clovers" , "9 Of Clovers" , "10 Of Clovers" , "Jack Of Clovers" ,
"Queen Of Clovers" , "King Of Clovers" , "Ace Of Spades" , "2 Of Spades" , "3 Of Spades" , "4 Of Spades" , "5 Of Spades" ,
"6 Of Spades" , "7 Of Spades" , "8 Of Spades" , "9 Of Spades" , "10 Of Spades" , "Jack Of Spades" ,
"Queen Of Spades" , "King Of Spades"};
}
public String getCard ()
{
randomNumber = (int) (Math.random() * 51) + 1;
String tempCard;
if (deck[randomNumber] != null)
{
tempCard = deck[randomNumber];
deck[randomNumber] = ("");
return (tempCard);
}
else
{
while (deck[randomNumber] == null)
{
randomNumber = (int) (Math.random() * 51) + 1;
}
tempCard = deck[randomNumber];
deck [randomNumber] = ("");
return (tempCard);
}
}
}
这是一个运行我的甲板课程的测试程序:
import hsa.Console;
public class DeckTest {
static Console c;
public static void main(String[] args) {
//The Console
c = new Console();
Deck Card = new Deck();
c.println(Card.getCard());
c.println(Card.getCard());
c.println(Card.getCard());
c.println(Card.getCard());
c.println(Card.getCard());
c.println(Card.getCard());
c.println(Card.getCard());
c.println(Card.getCard());
c.println(Card.getCard());
c.println(Card.getCard());
c.println(Card.getCard());
c.println(Card.getCard());
c.println(Card.getCard());
c.println(Card.getCard());
c.println(Card.getCard());
c.println(Card.getCard());
c.println(Card.getCard());
c.println(Card.getCard());
c.println(Card.getCard());
c.println(Card.getCard());
c.println(Card.getCard());
}
}
答案 0 :(得分:1)
这项测试是徒劳的:
deck[randomNumber] != null
因为你所有的牌组元素都不是空的,你用""替换抽出的牌,这是空字符串,但不是空的。
使用
deck [randomNumber] = null;
还应该改进循环。
private Random rand = new Random();
public String getCard () {
String tempCard = null;
do {
int r = rand.nextInt( deck.length );
tempCard = deck[r];
deck[r] = null;
} while( tempCard == null );
return tempCard;
}
应该添加一个测试,以便不要试图绘制比甲板上更多的东西。
答案 1 :(得分:0)
使用您的代码可以改进一些事项。
要解决您的问题:""
与null
不同。前者是非空的空字符串。后者是指向什么都没有的指针。您将需要使用后者使您的空检查str == null
按预期工作。
数组是0索引的。出于某种原因,在你的随机数字中你加1,使得心灵之王成为一张永远无法选择的牌。你想要的是确保你乘以元素数量的大小。这将从[0, size)
创建一个均匀分布的数字,并使用强制转换为整数将为您提供正确的数字。
我还建议使用while循环查看do-while循环而不是if语句。这将大大清理您的代码。