Home > Software design >  Trying to shuffle a custom Stack data structure
Trying to shuffle a custom Stack data structure

Time:07-18

I have been working on a project that simulates the "war" card game and made an original main deck and have been trying to get it shuffled with my custom stack class. I tried dividing the deck into four separate piles and using a randomized switch statement to add all the cards to one full pile similar to how people shuffle in trading card games. I have been receiving a nullPointer exception on my random number instantiation and am lost on how to fix it. I would appreciate any help!

        LinkedStack<Card> pileOne = new LinkedStack<Card>();
        LinkedStack<Card> pileTwo = new LinkedStack<Card>();
        LinkedStack<Card> pileThree = new LinkedStack<Card>();
        LinkedStack<Card> pileFour = new LinkedStack<Card>();
        
        int origSize = this.cards.size();
        
        for(int i = 0; i < 52; i   ) { // 52 cards in the deck (supposed to be)
            if(this.cards.isEmpty() == false) {
                pileOne.push(this.cards.peek());
                this.cards.pop();
            }
            if(this.cards.isEmpty() == false) {
                pileTwo.push(this.cards.peek());
                this.cards.pop();
            }
            if(this.cards.isEmpty() == false) {
                pileThree.push(this.cards.peek());
                this.cards.pop();
            }
            if(this.cards.isEmpty() == false) {
                pileFour.push(this.cards.peek());
                this.cards.pop();
            }
        }
        
        while(pileOne.size() != origSize) {
            int randNum = rand.nextInt(3); // <- nullpointer exception
            
            switch(randNum   1) {
                case 1:
                    if(pileTwo.isEmpty() == false) {
                        pileOne.push(pileTwo.peek());
                        pileTwo.pop();
                    }
                    break;
                case 2:
                    if(pileThree.isEmpty() == false) {
                        pileOne.push(pileThree.peek());
                        pileThree.pop();
                    }
                    break;
                default:
                    if(pileFour.isEmpty() == false) {
                        pileOne.push(pileFour.peek());
                        pileFour.pop();
                    }
                    break;
            }           
        }

CodePudding user response:

Maybe you haven't instantiated rand field. Local variables must be initialized if you want to use them, but it isn't the same for instance or static fields. So if you try to run a method on an undefined reference, you'll get a NullPointerException.

public Random rand = new Random();
  • Related