当我调用要在洗牌方法中使用的卡片数组时,它就像一个魅力:
Card [ ] cards = new Card[52]; //I create my array here, outside of any method
Random rnGen = new Random( );
public Deck( ) //Here is where I declare all the values for my array elements
{
cards[0] = new Card(11,"ACE","CLUB");
cards[1] = new Card(2,"TWO","CLUB");
cards[2] = new Card(3, "3", "CLUB");
cards[3] = new Card(4, "4", "CLUB");
cards[4] = new Card(5, "5", "CLUB");
... //52 statements declaring every single card.
}
public void shuffle( ) //This method is able to draw
{ //from the array with no problems
Card temp = new Card( );
for(int k = 0; k < 7000; k++;
{
f = rnGen.nextInt(52);
s = rnGen.nextInt(52);
temp = cards[f]; //Calling in elements from array
cards[f] = cards[s]; //and it works
cards[s] = temp;
}
}
但是当我尝试从数组中调用顶部元素时,问题出现了:
public Card getTopCard( )
{
Card top = new Card( );
top = card[0]; //This is the line that has the error
return top;
}
错误指出:“需要数组,但找到了卡”
为什么我的 shuffle() 方法可以毫无问题地访问我的数组,但我的 topcard() 方法却不能? 我没有做任何不同的事情,我的数组仍然在类的另一部分声明。
如果您能告诉我为什么会出现这种情况,我将非常感激,因为我实际上想了解为什么这是一个错误。
最佳答案
您将卡片数组定义为:
Card [ ] cards = new Card[52];
^---^
但稍后您想要访问:
top = card[0];
我不知道卡应该是什么,但我相信您想要访问卡
而不是卡
。
关于java - 为什么我的某些方法可以访问创建的数组,而其他方法则不能? (JAVA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26940726/