0

Every time I increment the below to update the created by my method, I get a Exception in thread "main" java.lang.NullPointerException error. I have no clue what's causing this, perhaps it's the "do" loop? I've tried everything I can and am not aiming to import any packages

userCardsCount = 2;
boolean trueScore = userSum <= 21;

do{    
    displayCards(true);

    // User turn
    int i = 2;

    System.out.println("\nUSER'S TURN");
    System.out.print("Draw new card (Y/N): ");
    input = br.readLine();

    if(input.equals("y") || input.equals("Y") || input.equals("yes") || input.equals("YES")) {
        userCardsCount++;
        userCards[i] = deck.drawCard();
        userSum += userCards[i].value;


        System.out.print("\n--> User drew a " + "[" + userCards[i].value + "]\n");
        //i++;
    } else if(input.equals("n") || input.equals("N") || input.equals("no") || input.equals("NO")) {
         // You stay as you are and go to the computer's turn
         System.out.println("--> User stays.");   
    } 
    else {
        System.out.println("\t--> Umm please retry input");
    }
} while(trueScore);

METHOD

public static void displayCards(boolean showHidden)
{
    if(showHidden) {
        System.out.print("Computer's cards: [" + computerCards[0].name + "]");
    } else {
        System.out.print("Computer's cards: [X]");
    }
    for(int i = 1; i < computerCardsCount; i++) {
        System.out.print("[" + computerCards[i].name + "]");
    }
    if(showHidden) {
        System.out.print(" (sum: " + computerSum + ")");
    }

    System.out.print("\nUser's cards: ");
    for(int i = 0; i < userCardsCount; i++) {
        System.out.print("[" + userCards[i].name + "]");
    }
    System.out.print(" (sum: " + userSum + ")");

    System.out.print("\n");
}

Any suggestions?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Sterling King
  • 163
  • 1
  • 3
  • 13
  • 1
    Well where are you getting the exception? What does the stack trace suggest? Have you debugged the code at all? – Jon Skeet Dec 14 '15 at 18:36
  • I suggest you look at the line which the stack trace says is the cause of the Exception. I also suggest stepping through the code in your debugger to help debug your code. The debugger is particularly useful in working out why you get an NPE. – Peter Lawrey Dec 14 '15 at 18:39

2 Answers2

1

You should look at your array: computerCards. You seem to be entering that method with true always, so you will always call computerCards[0].name which might be empty. You should put a break point at the start of that method, and then debug to see if you have a value in the 0th position.

theCJCsoccer
  • 601
  • 8
  • 29
1

At the end of file br.readLine() will return null. And your next equals breaks.

Jan
  • 13,738
  • 3
  • 30
  • 55