【问题标题】:Why can some of my methods access an array created but others cannot? (JAVA)为什么我的一些方法可以访问创建的数组而其他方法不能? (JAVA)
【发布时间】:2014-11-14 23:48:07
【问题描述】:

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

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() 方法不能? 我没有做任何不同的事情,我的数组仍然在类的另一部分声明。

如果您能告诉我为什么会这样,我将非常感激,因为我真的想了解为什么这是一个错误。

【问题讨论】:

  • 您显示的代码中没有“卡片”变量。
  • 这是什么语言? c#?
  • 发布完整代码可能会有所帮助,因为您所展示的内容没有意义。
  • 你有一个数组叫作洗牌的卡片,但是 getTopCard 中的卡片(没有 s)是卡片的一个实例,而不是一个数组。
  • 啊,好吧,只是一个愚蠢的错误。非常感谢您帮助我了解这一点

标签: java arrays methods required


【解决方案1】:

您将卡片数组定义为:

Card [ ] cards = new Card[52];
         ^---^

但是以后你想访问:

top = card[0];

我不知道应该是什么卡,但我相信您想访问cards 而不是card

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-02
    • 2011-12-08
    • 2023-03-11
    • 2013-07-13
    • 2014-03-28
    • 2022-12-06
    • 2019-11-17
    • 1970-01-01
    相关资源
    最近更新 更多