Informatiker Board (http://www.informatikerboard.de/board/index.php)
- Themengebiete (http://www.informatikerboard.de/board/board.php?boardid=1)
--- Praktische Informatik (http://www.informatikerboard.de/board/board.php?boardid=6)
---- Softwaretechnik (http://www.informatikerboard.de/board/board.php?boardid=18)
----- Null Pointer Exception - aber warum? (http://www.informatikerboard.de/board/thread.php?threadid=2702)


Geschrieben von Java_Beginner am 22.12.2015 um 20:03:

  Null Pointer Exception - aber warum?

Meine Frage:
Hallo :-)

Ich habe ein Programm geschrieben, dass einfach ein Buch auf einen Stapel legen soll. Leider bekomme ich immer eine NullPointer - Exception. Woran liegt das?

Und angenommen, ich möchte nicht nur Bücher auf meinen Stapel legen, sondern auch andere Gegenstände: Dann schreibe ich für jeden Gegenstand eine Klasse und rufe dann zur Laufzeit die jeweilige Klasse auf (also Polymorphie?)

Vielen Dank.

Meine Ideen:
Mein Code:

code:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
public class StackTest1 
{
    public static void main(String[] args) 
    {
        Stack myStack = new Stack (1);
        myStack.push(new Book("Kindheitstraum", "Horst Meier"));
        System.out.println(myStack.array[0]);
    }
}

class Stack
{
    private int top = 0; 
    Book [] array;
    int groesseStack=0;
    
    public Stack (int groesseStack)
    {
        this.groesseStack = groesseStack; 
    }
        
    public Book push (Book element)
    {
        return array[top++] = element;
    }
}


class Book
{
    private String titel;
    private String author;
    
    public Book (String titel, String author)
    {
        this.titel = titel;
        this.author = author;
    }
}




Geschrieben von eulerscheZahl am 22.12.2015 um 21:06:

 

Du musst das Array auch initialisieren:
Book[] array = new Book[10];

Und wenn du die Polymorphie nutzen willst, erstellst du Klassen, für Kinderbuch und Sachbuch, die jeweils von Book erben.


Forensoftware: Burning Board, entwickelt von WoltLab GmbH