Why can some of my methods access an array created but others cannot? (JAVA)

46 views Asked by At

When I call the array of cards to be used in my shuffle method, it works like a charm:

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;
       }
  }

But then the problem arises when I try to call in the top element from the array:

public Card getTopCard( )
  {
    Card top = new Card( );
    top = card[0]; //This is the line that has the error
    return top;
  }    

The error states: "array required, but Card found"

Why can my shuffle() method access my array no problem, but my topcard() method cannot? I haven't done anything different, my array was still declared in another part of the class.

If you can enlighten me as to why this is the case I would be very appreciative because I actually want to understand why this is an error.

1

There are 1 answers

0
Marko Gresak On BEST ANSWER

You define your card array as:

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

But later you want to access:

top = card[0];

I don't know what card is supposed to be, but I do believe you want to access cards rather than card.