首页 > 解决方案 > 创建 Do-While 循环后修复 java.lang.NullPointerException

问题描述

我遇到了 java.lang.NullPointerException 错误,并希望了解有关如何修复错误的信息。我知道它有一个问题是空的,但我不知道是什么。

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

这是我的一些代码,可以查看我现在正在做什么以及发生错误的位置。我能做些什么来阻止这个错误的发生?

第 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;

    }
}

第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;

    }

    }

第 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;

    }
}

堆栈跟踪?

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

这是我对 case3 和整个其他方法调用进行更改后的 getHistogram() 替代选项。使用这个我遇到了 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

这些错误发生在

newDeck.getHistogram ( numberOfCards );

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

String[] histogramDeck = dealCards ( numberOfCardsDealt );

标签: java

解决方案


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

摘要:您需要调查 dealtDeck - 当您初始化它时,它包含什么值以及您在哪里更新它。

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]);

PS重现错误:运行程序,然后输入西装和排名,然后选择选项3 - 接收NullPointerException。


推荐阅读