-2

I've run into the java.lang.NullPointerException error and would appreciate information on how to go about fixing the error. I understand that it's having an issue with something being null but I cannot figure out what.

Basically, the issue only began to occur once I tried to put together a Do-While loop. If I remove the loop and edit the code so as to only run once when the method getHistogram() has been called the error does not occur.

Here is some of my code to get a look at what i'm doing as of right now and where the error occurs. What can I do to stop this error from happening?

Page 1.

public class MainClass {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        int optionSelected;
        int NumberOfSuits;
        int NumberOfRanks;
        int numberOfCardsDealt = 0;
        int SizeOfDeck;
        int numberOfCards;


           System.out.printf( "How many suits? " );
           NumberOfSuits = getDecision();

           System.out.printf( "How many ranks? " );
           NumberOfRanks = getDecision();

           SizeOfDeck = NumberOfSuits * NumberOfRanks;

        DeckofCards newDeck = new DeckofCards();
        newDeck.setDeckofCards(NumberOfRanks, NumberOfSuits);
        newDeck.createDeckofCards();

        do {
            System.out.println ( newDeck.toString() );
            System.out.printf ( "1=Shuffle, 2=Deal 1 Hand, 3= Deal 100000 Times,"
                    + "4=Quit: " );
            optionSelected = getDecision();


            switch ( optionSelected ) {
                case 1:
                    newDeck.shuffleDeckofCards();
                    break;
                case 2:
                    numberOfCards = getCardDecision();
                    numberOfCardsDealt = numberOfCardsDealt + numberOfCards;

                    if ( SizeOfDeck > numberOfCardsDealt ) {
                        String[] dealCards = newDeck.dealCards ( numberOfCards );
                        for ( String printCardsDealt : dealCards ) {
                            System.out.println ( printCardsDealt );
                        } 

                    }
                    else {
                        System.out.println ( "Deck must be re-shuffled" );
                        numberOfCardsDealt = 0;
                        break;
                    }
                    break;
                case 3:
                    numberOfCards = getCardDecision();
                    int[] histogram = newDeck.getHistogram( numberOfCards );
                        for ( int printHistogram : histogram ) {
                            System.out.println ( printHistogram );
                        }
                    break;

                }
        } while ( optionSelected != 4 );




    }

    public static int getDecision() {
        String numberMatch;
        int optionSelected = 0;
        Scanner in = new Scanner(System.in);

        do { 
            numberMatch = in.next();
                if( numberMatch.matches("[0-9]+" ) ){ 
                    optionSelected = Integer.parseInt( numberMatch );
                }
                if ( optionSelected < 1 || optionSelected > 9 ){
                    System.out.println("Try again!");
                }
        } while ( optionSelected < 1 || optionSelected > 9 );

        return optionSelected;

    }

    public static int getCardDecision() {
        String numberMatch;
        int optionSelected = 0;
        Scanner in = new Scanner(System.in);

        do { 
            System.out.printf ( "How many cards? " );
            numberMatch = in.next();
                if( numberMatch.matches("[0-9]+" ) ){ 
                    optionSelected = Integer.parseInt( numberMatch );
                }
                if ( optionSelected < 1 || optionSelected > 9 ){
                    System.out.println("Try again!");
                }
        } while ( optionSelected < 1 || optionSelected > 9 );

        return optionSelected;

    }
}

Page 2.

public class DeckofCards {
    private int NumberOfRanks;
    private int NumberOfSuits;
    private int SizeOfDeck;
    private String newDeck[];
    private String dealThisDeck[];
    private int howManyCards;
    private int cardsDealtTotal = 0;
    private int numberOfCardsDealt;
    private int numberOfCards;
    private String dealtDeck[];
    private int CardsDealtInTotal = 0;
    private int histoSum[];

    public void setDeckofCards ( int NumberOfRanks, int NumberOfSuits ) {
        this.NumberOfRanks = NumberOfRanks;
        this.NumberOfSuits = NumberOfSuits;


    }

    public void createDeckofCards() {
        SizeOfDeck = NumberOfRanks * NumberOfSuits;

        Cards newCard = new Cards();

        newCard.setCards ( NumberOfRanks, NumberOfSuits );

        newDeck = new String [ SizeOfDeck ];

        int counter = 0;
        for (int whatSuit = 1; whatSuit <= NumberOfSuits; whatSuit++) {
            for (int rank = 1; rank <= NumberOfRanks; rank++) {
                newDeck[counter++] = newCard.createCard(rank, whatSuit);
            }
        } 
    }
    public void shuffleDeckofCards() {

        int index;
        int length = newDeck.length;
        String temp;

        Random random = new Random();

        for ( int i = length - 1; i > 0; i-- ) {
            index = random.nextInt(i+1);
            temp = newDeck[index];
            newDeck[index] = newDeck[i];
            newDeck[i] = temp;
        }
        }

    public String[] dealCards( int howManyCards ) {
        this.howManyCards = howManyCards;
        dealtDeck = new String[ howManyCards ];

        System.arraycopy(newDeck, cardsDealtTotal, dealtDeck, 0, howManyCards);

        cardsDealtTotal = cardsDealtTotal + howManyCards;

        return dealtDeck;

    }

    @Override
    public String toString() {
        return ( "Deck of " + SizeOfDeck + "cards: low = 1 high = " + 
                SizeOfDeck + "top = Card " + newDeck [ cardsDealtTotal ] );
    }

    public int[] getHistogram( int numberOfCardsDealt ) {
        int sum = 0; //initialize sum as 0
        int count = 0; //initialize count 0
        this.numberOfCards = numberOfCardsDealt - 1; //Equivalent array position to cards dealt

        DeckofCards histoDeck = new DeckofCards();


        do {
            CardsDealtInTotal = CardsDealtInTotal + numberOfCards;

            if ( SizeOfDeck < CardsDealtInTotal ) {
                shuffleDeckofCards();
                CardsDealtInTotal = 0;       
        }

        for ( int i = 0; i <= numberOfCards; i++ ) {    
            sum = sum + histoDeck.getSumOfHand( dealtDeck[i]); //Check and send each position of hand to be added

            histoSum[sum] +=1; //Based on sum add 1 to that position in the array

            }    
        count+= 1;
        } while ( count != 2 );   

        return histoSum;

    }

    public int getSumOfHand( String a) {
        int value = 0;
        String s;
        s = a;
        Pattern pattern = Pattern.compile("^S([\\d]+)R([\\d]+)$");
        Matcher matcher = pattern.matcher(s);
        if(matcher.find()){
        value = (Integer.parseInt(matcher.group(1))*Integer.parseInt(matcher.group(2)));

        }

        return value;

    }

    }

Page 3.

public class Cards {

    private int numberOfRanks;
    private int numberOfSuits;
    private int createCard;
    private String theNumber;
    private int whatSuit;
    private String theSuit;
    private String theCard;

    public void setCards( int numberOfRanks, int numberOfSuits ) {
       this.numberOfRanks = numberOfRanks;
       this.numberOfSuits = numberOfSuits;

    }

    public String createCard( int newCard, int whatSuit ) {


        createCard = newCard;
        theNumber = Integer.toString( createCard );
        theSuit = Integer.toString ( whatSuit );

        theCard = ( "S" + theSuit + "R" + theNumber );

        return theCard;

    }
}

StackTrace?

Exception in thread "main" java.lang.NullPointerException
at MainClass.DeckofCards.getHistogram(DeckofCards.java:105)
at MainClass.MainClass.main(Assignment4.java:72)
C:\Users\mikel\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1

This is my alternative option of the getHistogram() after making changes to case3 and the entire other method call. Using this I run into an issue with ArrayIndexOutOfBoundsException.

        case 3:
            numberOfCards = getCardDecision();
            newDeck.getHistogram( numberOfCards );
                //for ( String printHistogram : histogram ) {
                  //  System.out.println ( printHistogram );
                //}
            break;

public void getHistogram( int numberOfCardsDealt ) {
    int sum = 0;
    int count = 0;
    this.numberOfCardsDealt = numberOfCardsDealt;
    this.numberOfCards = numberOfCardsDealt - 1;
    CardsDealtInTotal = numberOfCardsDealt + numberOfCards;



    DeckofCards histoDeck = new DeckofCards();

    do {
        if ( SizeOfDeck > CardsDealtInTotal ) {
            String[] histogramDeck = dealCards ( numberOfCardsDealt );

            for ( int i = 0; i <= numberOfCards; i++ ) {

                sum = sum + histoDeck.getSumOfHand( histogramDeck[i]);
                System.out.println ( sum );

        }

    }
    else {
        shuffleDeckofCards();
        CardsDealtInTotal = 0;       

    }
    count+= 1;
    } while ( count != 6 );


   }  


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
    at java.lang.System.arraycopy(Native Method)
    at MainClass.DeckofCards.dealCards(DeckofCards.java:74)
    at MainClass.DeckofCards.getHistogram(DeckofCards.java:101)
    at MainClass.MainClass.main(MainClass.java:72)
C:\Users\mikel\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1

These errors occur at

newDeck.getHistogram ( numberOfCards );

System.arraycopy ( newDeck, cardsDealtTotal, dealtDeck, 0, howManyCards);

String[] histogramDeck = dealCards ( numberOfCardsDealt );
Twissted
  • 67
  • 1
  • 9
  • 1
    Post stacktrace. Also, `newDeck` and `dealtDeck` are both null. – k_ssb Jun 22 '18 at 18:33
  • nullPointer will not be thrown when something gets initialized to null. All objects in Java are nullable, so i guess you have some nullvalues in newDeck. You use method chaining, are you sure newDeck returns `this` ? – JohEker Jun 22 '18 at 18:37
  • If I was able to understand that post which I already read through in order to try and fix my code I wouldn't be posting another question in order to hopefully get some better insight or an answer in different wording to find a solution @SergeiSirik but I appreciate your input. I will take a look into newDeck and see if that is my issue JohEker, thank your for your input – Twissted Jun 22 '18 at 18:43
  • I'll take a look at Stacktrace, I am not 100% sure how to debug my instructor went over it quite briefly. I'll see if I can find a video that will help me out a bit more. I'm looking into newDeck and dealtDeck since you think they are null I'll see what's going on there. Appreciate the input @pkpnd – Twissted Jun 22 '18 at 18:45
  • @Twissted By the way, if you post your **complete** code, we can help you more. Right now, no one can see where `newDeck` or `dealtDeck` come from because they aren't declared in your posted code. – k_ssb Jun 22 '18 at 18:47
  • That is fair, it's just a lot of bloody code to post. newDeck and dealtDeck are both private String newDeck[] and dealtDeck[]. newDeck[] is initialized within a method which places card values within the array. dealtDeck[] is a copy of a user inputted number of cards to represent a hand of dealt cards. The reason for that is so I can keep track of the number of cards left in the deck to be dealt. – Twissted Jun 22 '18 at 19:00
  • @pkpnd I have updated the code snippets to include where newDeck and dealtDeck is created if that helps at all? Also I was able to make this code work when I just ran it through one time. But as soon as I attempted to create a loop of it the error would occur and I cannot seem to figure out why. – Twissted Jun 22 '18 at 19:02
  • @Twissted First of all, I didn't ask for code snippets, I asked for **complete** code. Don't break it up, don't cut anything out, the **entire** code as-is. Second, since you've apparently fixed your NullPointerException, your new issues with a loop are an entirely different question. Questions on StackOverflow should be as focused as possible. – k_ssb Jun 22 '18 at 19:07
  • Is it possible that because i'm returning the histogram[sum] it doesn't know where I want that number saved? This is incredibly confusing. – Twissted Jun 22 '18 at 19:07
  • Alright one second – Twissted Jun 22 '18 at 19:08
  • @pkpnd Edited, now like I mentioned previously if I was to remove the do-while loop and play around with it again I could most likely get my code to work one time around but including the do-while loop seems to cause the error – Twissted Jun 22 '18 at 19:14
  • Sorry, you need to post a new question. Your question title and text say you have a NullPointerException but now that's fixed and you have issues with a loop. As I said, that's a different question. (And once again, no one can help you without a stacktrace...) – k_ssb Jun 22 '18 at 19:17
  • NullPointerException has not been fixed? I can only temporarily fix it if I completely remove the loop which is not what I am trying to do. I will look at the stacktrace and see if I can figure out how to do that now – Twissted Jun 22 '18 at 19:25

1 Answers1

0

I've compiled and run your program... I combine all texts in one file, so I show full lines with errors.

SUMMARY: You need to investigate dealtDeck - when you initialize it, what values it contains and where you update it.

Exception in thread "main" java.lang.NullPointerException
    at DeckofCards.getHistogram(MainClass.java:207)
    at MainClass.main(MainClass.java:64)

this 207 line:

       sum = sum + histoDeck.getSumOfHand( dealtDeck[i]); //Check and send each position of hand to be added

I initiate array to go futher:

private String dealtDeck[] = new String[1000];

Next error

Exception in thread "main" java.lang.NullPointerException
    at java.util.regex.Matcher.getTextLength(Unknown Source)
    at java.util.regex.Matcher.reset(Unknown Source)
    at java.util.regex.Matcher.<init>(Unknown Source)
    at java.util.regex.Pattern.matcher(Unknown Source)
    at DeckofCards.getSumOfHand(MainClass.java:224)
    at DeckofCards.getHistogram(MainClass.java:207)
    at MainClass.main(MainClass.java:64)

Occurs here:

    Pattern pattern = Pattern.compile("^S([\\d]+)R([\\d]+)$");
    Matcher matcher = pattern.matcher(s);  //<----- here from histoDeck.getSumOfHand( dealtDeck[i]);

P.S. To reproduce error: run program, then enter suits and ranks, THEN choose OPTION 3 - to receive NullPointerException.

Serge Breusov
  • 1,206
  • 3
  • 8
  • 23
  • My only other option is to completely remove the idea of using int[] which I guess is technically pointless because I can print out a statement from the method getHistogram(). By doing so I then run into a further issue where I cannot seem to reshuffle the deck using my loop and end up with an error of ArrayIndexOutOfBoundsException, which I have run into and fixed previously once. So I am trying to work with it again. If all else fails I think I may just re-shuffle the deck after every hand dealt even though that was not what I wanted to do initially. – Twissted Jun 22 '18 at 20:06
  • Updated to show what changes I have currently made if you want to take a quick peak. I'm still testing to try and figure out my issue. I also need to change up my variable names as they are getting confusing.. – Twissted Jun 22 '18 at 20:12