简体   繁体   中英

Difficulty calling ArrayLists and Methods from another Class in Java

first time poster, longtime lurker.

I'm a second year Computer Science student trying to code a Blackjack game. It's not a homework assignment, it's just a for fun project. It's not done so the game itself is not ready, so please ignore that section. I spent about two hours searching SO for an answer but couldn't compare other users' similar problems to my own so I'm deciding to post my issue.

My problem is the 'deck' ArrayList. From my Blackjack.java file, no matter what I do, I cannot call it, I cannot call any methods in my Card class, I cannot manipulate it, I can't seem to do anything without receiving some sort of error.

public class Blackjack {
    public int bet;
    public int earnings = 0;
    public int total = 100;
    public boolean inputNeeded = true;

    public Blackjack() {
        Scanner s = new Scanner(System.in);

        System.out.println("               Welcome to Blackjack.");
        System.out.println("             Enter any key to continue.");
        System.out.println("         Otherwise, please type Exit to quit.");

        while (!s.nextLine().toString().toLowerCase().equals("exit")) //Main Game Loop - Only ends when user types Exit.
        {
            while (inputNeeded) {
                System.out.println("You currently have $" + total + ".");
                System.out.print("Please place your bets now. (Min $10): $");

                if (s.hasNextInt()) {
                    bet = s.nextInt();
                    String betString = String.valueOf(bet);
                    inputNeeded = false;

                    if (bet < 10 || bet % 5 != 0) {
                        System.out.println("Your bet is not valid. Your bet must be a minimum of $10 and be a factor of 5.");
                        System.out.println("");
                        inputNeeded = true;
                    }
                } else {
                    System.out.println("Your bet is not valid. Your bet must be a minimum of $10 and be a factor of 5.");
                    System.out.println("");
                }
            }
            inputNeeded = true; 

            /*
             * RESERVED SPACE (stuff to-do)
             * 
             * Deal two cards to dealer and player.
             * Flip cards, add totals
             * If dealer has ace, prompt user if he wants insurance incase dealer blacjack
             * Main loop, as long as neither player has blackjack, prompt user to hit, stay, double down etc.
             * Once loop exits, calculate bets, add into totals. 
             * Increase count of how many games it's been, shuffle the decks at X games depending on howManyDecks (card.java)
             * 
             * RESERVED SPACE (stuff to-do)
             * 
             */
            deck.shuffle();

            break; //until game is finished
        }

        System.out.print("Thank you for playing!");
    }

    public static void main(String[] args) {
        Blackjack game = new Blackjack();
    }
}

And the card class (I know I could have done the 52 cards in a loop but for simplicity's sake I decided not to). From what I read, if I don't want to make static methods, I have to make 'getter' methods. I'm not quite sure how return methods will help me, say, to shuffle the deck from the blackjack class, or to draw cards from the blackjack class (not implemented yet), as those methods would have void as their return type. I'm not even sure if my getter methods are correct, as I've never tried to 'get' a parameter that's required for the constructor before.

public class Card
    extends Blackjack //Do I need to extend this? <---- not sure
{
    public String name;
    public int value;
    public String suit;
    public int howManyDecks = 8; //most casino's use 8 decks for blackjack

    public Card(String n, int v, String s) {
        name = n;
        value = v;
        suit = s;

        ArrayList<Card> discard = new ArrayList<Card>(); //this will be for any card that is not currently in the deck, I could have called it 'temp'
        ArrayList<Card> deck = new ArrayList<Card>(howManyDecks * 52);

        for (int i = 0; i < howManyDecks; i++) {
            deck.add(new Card("Ace", 1, "Hearts"));
            deck.add(new Card("2", 2, "Hearts"));
            deck.add(new Card("3", 3, "Hearts"));
            deck.add(new Card("4", 4, "Hearts"));
            deck.add(new Card("5", 5, "Hearts"));
            deck.add(new Card("6", 6, "Hearts"));
            deck.add(new Card("7", 7, "Hearts"));
            deck.add(new Card("8", 8, "Hearts"));
            deck.add(new Card("9", 9, "Hearts"));
            deck.add(new Card("10", 10, "Hearts"));
            deck.add(new Card("Jack", 10, "Hearts"));
            deck.add(new Card("Queen", 10, "Hearts"));
            deck.add(new Card("King", 10, "Hearts"));
            deck.add(new Card("Ace", 1, "Spades"));
            deck.add(new Card("2", 2, "Spades"));
            deck.add(new Card("3", 3, "Spades"));
            deck.add(new Card("4", 4, "Spades"));
            deck.add(new Card("5", 5, "Spades"));
            deck.add(new Card("6", 6, "Spades"));
            deck.add(new Card("7", 7, "Spades"));
            deck.add(new Card("8", 8, "Spades"));
            deck.add(new Card("9", 9, "Spades"));
            deck.add(new Card("10", 10, "Spades"));
            deck.add(new Card("Jack", 10, "Spades"));
            deck.add(new Card("Queen", 10, "Spades"));
            deck.add(new Card("King", 10, "Spades"));
            deck.add(new Card("Ace", 1, "Diamonds"));
            deck.add(new Card("2", 2, "Diamonds"));
            deck.add(new Card("3", 3, "Diamonds"));
            deck.add(new Card("4", 4, "Diamonds"));
            deck.add(new Card("5", 5, "Diamonds"));
            deck.add(new Card("6", 6, "Diamonds"));
            deck.add(new Card("7", 7, "Diamonds"));
            deck.add(new Card("8", 8, "Diamonds"));
            deck.add(new Card("9", 9, "Diamonds"));
            deck.add(new Card("10", 10, "Diamonds"));
            deck.add(new Card("Jack", 10, "Diamonds"));
            deck.add(new Card("Queen", 10, "Diamonds"));
            deck.add(new Card("King", 10, "Diamonds"));
            deck.add(new Card("Ace", 1, "Clubs"));
            deck.add(new Card("2", 2, "Clubs"));
            deck.add(new Card("3", 3, "Clubs"));
            deck.add(new Card("4", 4, "Clubs"));
            deck.add(new Card("5", 5, "Clubs"));
            deck.add(new Card("6", 6, "Clubs"));
            deck.add(new Card("7", 7, "Clubs"));
            deck.add(new Card("8", 8, "Clubs"));
            deck.add(new Card("9", 9, "Clubs"));
            deck.add(new Card("10", 10, "Clubs"));
            deck.add(new Card("Jack", 10, "Clubs"));
            deck.add(new Card("Queen", 10, "Clubs"));
            deck.add(new Card("King", 10, "Clubs"));
        }
    }

    public void shuffle() {
        ArrayList<Card> temp = new ArrayList<Card>();
        while (!deck.isEmpty()) {
            int loc = (int) (Math.random() * deck.size());
            temp.add(deck.get(loc));
            deck.remove(loc);
        }
        deck = temp;
    }

    public Card getDeck() {
        return deck;
    }

    public Sting getCardName(int arrayIndex) {
        return deck(arrayIndex, Name);
    }

    public int getCardValue(int arrayIndex) {
        return deck(arrayIndex, Value);
    }

    public String getCardSuit(arrayIndex, Suit);
    {
        return deck(arrayIndex, Suit);
    }
}

Try to run:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    deck cannot be resolved

    at Blackjack.<init>(Blackjack.java:61)
    at Blackjack.main(Blackjack.java:72)

Thanks for all the help in advance!

Lots of problems...

  • You're trying to run uncompilable code -- never do this. Fix the compilation problems first before ever trying to run a program.
  • You're trying to call a method on a variable that has not been declared in the class. Blackjack needs a deck variable that is initialized if you're ging to call a method on it.
  • I'd consider creating a Deck class that holds the ArrayList and that has all the behaviors (methods) of a deck of cards.
  • The Card class should not have a deck field. Logically, why would a Card need to know about the deck it's in.
  • Card should most definitely not extend Blackjack
  • Instead, Card should encapsulate the idea of a single Card, meaning its suit and its rank, and nothing else.
  • Later you could use a HashMap to associate each Card with an Image or ImageIcon if desired.
  • The Card/Deck concept is one of the canonical examples used when teaching enums, so borrow this idea -- make your Suit and your Rank into enums, and have your Card class hold a field of each of these enums.

Regarding,

What do you mean by trying to run uncompilable code?

Whenever you see this:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    deck cannot be resolved

It means precisely that: that you're trying to run code that won't compile. You must fix this at the compilation stage, not at the run stage.

I mean, without the deck.shuffle(); , it does compile and runs okay.

Then you must fix the deck.shuffle() error before re-trying to run the code.

Is it that the way this code is structured, trying to accomplish my goals will be impossible?

I would re-start from the beginning with cleaner classes, especially your Card class which is key to everything. Use enums like I suggested, read up on them here: Java enums tutorial .

"Blackjack needs a deck variable that is initialized if you're ging to call a method on it.", but I thought I could just use the Deck variable in the other class?

You can only call methods on fields that are within the scope of the calling code. This is a basic Java 101 concept so you'd best review how to call methods on classes. Your Blackjack class does not have a deck field, it simply doesn't exist in that class, and so you cannot call a method on a field or variable that does not exist.

Can't I reference arrays, objects, variables, static things, whatever you want etc from other classes one way or another? Sorry for my lack of understanding, I'm still very much a leaner.

These are basic questions that are beyond the confines of this site and suggest that you'd benefit from re-reviewing the introductory chapters of a decent Java book or tutorial. You won't regret doing this, believe me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM