Search code examples
javablackjack

']' expected when writing Blackjack method


 while (hitOrStay.equalsIgnoreCase("hit"))
      {

        Card temp[hitOrStayCounter] = cardDeck.deal(); // issue occurs on this line
        System.out.println("You are delt a " + temp[hitOrStayCounter].getBJ()); 
        hitOrStayCounter++;
        System.out.println("Would you like to hit again?"); 
        hitOrStay = ketboard.next(); 
      }

Here is the segment of my code with the problem. I'm getting a problem where it says that it is expecting a ']', and I've tried to fix it to no avail. Any suggestions?

 public Card deal()
 {
    nextCard++;
    return deck[nextCard-1];
 }  
public static void main(String[] args)  
  {
   int hitOrStayCounter=5;
   Bankroll money = new Bankroll();
   Deck cardDeck = new Deck(); 
   Scanner keyboard = new Scanner(System.in); 
   System.out.println("Would you like to play?"); 
   String playGame = keyboard.next(); 
   while (playGame.equalsIgnoreCase("yes")) 
   }

Also here is the specific error:

Error: ']' expected


Solution

  • The problem is that you're trying to declare an array size in the array definition. The array size should be initialized on the right side of the equal sign. Based on my knowledge of blackjack, I can provide these suggestions:

    • Use an ArrayList instead of an array. This should be done because an ArrayList can continue to expand while an array must be initialized to a specific size. This is needed since someone can hit as much as they want.
    • Put the ArrayList outside of your while loop. By defining the variable inside the while loop, it gets overwritten with each iteration of the loop.

    You can continue to use an array, but you should still declare and initialize it outside of the while loop. If you use an array, be sure to set a size that is large enough to handle multiple hits. You should use the following format if you continue to use an array:

    Card[] temp = new Card[x]