java - 为什么我的某些方法可以访问创建的数组,而其他方法则不能? (JAVA)

标签 java arrays methods required

当我调用要在洗牌方法中使用的卡片数组时,它就像一个魅力:

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/

相关文章:

java - Android unicode 西里尔文字符串在传入函数时变为 С

python - 创建一个可以访问参数和函数的装饰器

c++ - 如何计算排序数组中的重复数字

c++ - 如何在一个数组中保存更多指针

arrays - 如何在线性时间内对二进制数组进行排序?

java - 发送数据到一个方法并一一检查

Java:查找数组中 double 的平均值

java - 在 UDP 上发送和接收序列化对象

java - 如何通过 Java 程序设置要使用的 dns 服务器?

java - java中如何读取字符串的第二行