Du bist nicht angemeldet.

Stilllegung des Forums
Das Forum wurde am 05.06.2023 nach über 20 Jahren stillgelegt (weitere Informationen und ein kleiner Rückblick).
Registrierungen, Anmeldungen und Postings sind nicht mehr möglich. Öffentliche Inhalte sind weiterhin zugänglich.
Das Team von spieleprogrammierer.de bedankt sich bei der Community für die vielen schönen Jahre.
Wenn du eine deutschsprachige Spieleentwickler-Community suchst, schau doch mal im Discord und auf ZFX vorbei!

Werbeanzeige

1

08.05.2014, 18:31

NullPointerException Java

Hallo,
ich hab ein Problem: (Ja den Code da unten)

Quellcode

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
43
44
45
46
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;

import javax.swing.JPanel;


public class Pane extends JPanel {
    
    Cell[][] cells = new Cell[20][20];
    
    public Pane (){
        for (int x = 0;x <= cells.length; x++) {
            for (int y = 0;y <= cells[x].length; y++) {
                cells[x][y].isActive = false;
            }
        }
    }
    
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        
        for (int x = 0;x <= cells.length; x++) {
            for (int y = 0;y <= cells[x].length; y++) {
                
                if (cells[x][y].isActive) {
                    g.setColor(Color.BLACK);
                } else {
                    g.setColor(Color.WHITE);
                }
                
                g.fillRect(x * Cell.CELL_SIZE, y * Cell.CELL_SIZE, Cell.CELL_SIZE, Cell.CELL_SIZE);
            }
        }
    }
}

class Cell {
    static int CELL_SIZE = 16;
    
    public boolean isActive = false;
    public boolean isNext = false;
    
    
}


Warum wirft mir diese Zeile eine NullPointerException? >> cells[x][y].isActive = false; <<

Fehlermeldung:

Quellcode

1
2
3
4
Exception in thread "main" java.lang.NullPointerException
    at Pane.<init>(Pane.java:15)
    at Window.<init>(Window.java:13)
    at Window.main(Window.java:18)


MfG Chris und Danke im Voraus.

PS: Das soll mal Conways Game of Life werden.
LostLife ein 3D RPG - development

2

08.05.2014, 19:00

Du erzeugst ein Array mit Null-Referenzen. Du musst jedes Element auch erstellen.
"Theory is when you know something, but it doesn’t work. Practice is when something works, but you don’t know why. Programmers combine theory and practice: Nothing works and they don’t know why." - Anon

3

08.05.2014, 19:09

Ok hatte ich mir gedacht dann ist ja gut.

thx
LostLife ein 3D RPG - development

Sylence

Community-Fossil

Beiträge: 1 663

Beruf: Softwareentwickler

  • Private Nachricht senden

4

09.05.2014, 01:43

Das <= in der Bedingung der for-Schleifen wird dann als nächstes knallen...

5

09.05.2014, 06:19

Das ist schon gefixt ^^.

Nach der Null Pointer Exception kam eine Zugriffswarnung für das Array.

Christian
LostLife ein 3D RPG - development

Werbeanzeige