创建Do-While循环后,修复java.lang.NullPointerException

时间:2018-06-22 18:31:38

标签: java

我遇到了java.lang.NullPointerException错误,希望了解有关如何解决该错误的信息。我知道这是一个零值问题,但是我无法弄清楚是什么。

基本上,只有在我尝试将Do-While循环放到一起时,问题才开始出现。如果删除循环并编辑代码,以便仅在调用getHistogram()方法时运行一次,则不会发生错误。

这是我的一些代码,以查看我目前正在执行的操作以及发生错误的位置。我该怎么做才能阻止此错误的发生?

第1页。

Main

第2页。

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;

    }
}

第3页。

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;

    }

    }

StackTrace?

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;

    }
}

这是在对case3和整个其他方法调用进行更改之后,getHistogram()的替代选项。使用此方法,我遇到了ArrayIndexOutOfBoundsException的问题。

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

这些错误发生在

        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

1 个答案:

答案 0 :(得分:0)

我已经编译并运行了程序...我将所有文本合并到一个文件中,所以我显示带有错误的整行。

摘要:您需要研究DealdDeck-初始化时,它包含什么值以及在哪里更新。

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

这207行:

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

我初始化数组以进一步:

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

下一个错误

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)

出现在这里:

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

P.S。重现错误:运行程序,然后输入花色和等级,然后选择选项3-接收NullPointerException。