0
Card karte;
Stack <Card> kartenstapel;

 public Standard52() {

     /** this works*/
     this.karte = new Card(Suit.HEARTS,13);                       

     /** this throws a 0-pointer exception when I try to initial*/

     this.kartenstapel.addElement(new Card(Suit.HEARTS, 13));
     this.kartenstapel.addElement(new Card(Suit.HEARTS, 13));
     this.kartenstapel.addElement(new Card(Suit.HEARTS, 13));
     this.kartenstapel.addElement(new Card(Suit.HEARTS, 13));
 }

Why i get a null pointer exception when i try to inital it. Its more theorie then practice but i do not undersstand my failure maybe some of you can explain me where my mistake is.

  • 6
    Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – leopal Jan 03 '20 at 11:14
  • 1
    You have not initialized `kartenstapel` which is why it is throwing an exception. Initialize it by `Stack kartenstapel = new Stack<>();` and then proceed to run the code. It should work just fine. – Mohit Dodhia Jan 03 '20 at 11:16

3 Answers3

3

You need to initialize the Stack as well. So, it would be

public Standard52() {
    this.kartenstapel = new Stack<>();
    // now add elements
 }
Richard Robinson
  • 867
  • 1
  • 11
  • 38
1

You have to initialize the Stack collection:

Card karte;
Stack <Card> kartenstapel = new Stack<>(); // initialization to an empty stack

public Standard52() {

     /** this works*/
     this.karte = new Card(Suit.HEARTS,13);                       

     /** this should work as the kartenstapel is initialized */

     this.kartenstapel.addElement(new Card(Suit.HEARTS, 13));
     this.kartenstapel.addElement(new Card(Suit.HEARTS, 13));
     this.kartenstapel.addElement(new Card(Suit.HEARTS, 13));
     this.kartenstapel.addElement(new Card(Suit.HEARTS, 13));
 }
tmarwen
  • 15,750
  • 5
  • 43
  • 62
0

You need to initialize kartenstapel.

Stack <Card> kartenstapel = new Stack<>();
Vikas
  • 6,868
  • 4
  • 27
  • 41