我在处理中使用堆栈方法时遇到问题。我想存储在堆栈坐标中,然后将它们取出。
这是一段涉及我想要的代码
import java.util.ArrayList;
import java.util.Random;
import java.lang.Math;
import java.util.Stack;
Stack<Celda> pila=new Stack<Celda>();
int f1, f2, a, b, c, d, e, f, p, w, w1, w2,g,k;
int [][] laberinto;
int [] direcciones = new int [4];
int cols, rows;
int alto = 50;
int ancho = 50;
int celda = 10;
color co = color(175, 100, 220);
Celda[][] coordenada;
Celda[][] actual;
void setup(){
size( ancho*celda, (alto*celda));
background(50);
cols = width/celda;
rows = height/celda;
w = 10;
w1 = w - 1;
w2 = 2*w - 1;
f1= int(random(0,cols));
f2= int(random(0,rows));
c = f1/2;
d = f2/2;
e = cols-1;
g=rows-1;
laberinto = new int [cols][rows];
coordenada = new Celda[cols][rows];
actual = new Celda[cols][rows];
for(int i = 0; i < alto*celda; i++)
for(int j = 0; j < ancho*celda; j++){
fill(50);
rect(i*celda,j*celda,celda,celda);
}
}
void draw(){
p = 0;
if (c > 0) { if (laberinto[c-1][d] == 0) { direcciones[p++] = 1; }}
if (d > 0) { if (laberinto[c][d-1] == 0) { direcciones[p++] = 2; }}
if (c < e) { if (laberinto[c+1][d] == 0) { direcciones[p++] = 4; }}
if (d < g) { if (laberinto[c][d+1] == 0) { direcciones[p++] = 8; }}
if (p > 0) {//cuando p es mayor a cero hay una celda vacía
p = direcciones[floor(random(p))];
laberinto[c][d] += p;
switch(p) {
case 1:
rect(c*w-w, d*w, w, w);
laberinto[--c][d] = 1;
pila.push(coordenada[c][d]);
fill(co);
stroke(co);
line(c*w+w, d*w+1, c*w+w, d*w+w-1);
stroke(0);
k=1;
break;
case 2:
rect(c*w, d*w-w, w, w);
laberinto[c][--d] = 1;
pila.push(coordenada[c][d]);
fill(co);
stroke(co);
line(c*w+1, d*w+w, c*w+w-1, d*w+w);
stroke(0);
k=2;
break;
case 4:
rect(c*w+w, d*w, w,w);
fill(co);
laberinto[++c][d] = 1;
pila.push(coordenada[c][d]);
stroke(co);
line(c*w, d*w+1, c*w, d*w+w-1);
stroke(0);
k=3;
break;
case 8:
rect(c*w, d*w+w, w, w);
fill(co);
laberinto[c][++d] = 1;
pila.push(coordenada[c][d]);
stroke(co);
line(c*w+1, d*w, c*w+w-1, d*w);
stroke(0);
k=4;
break;
}
} else
{ int a=1,b=1;
actual[a][b]=pila.pop();
c = actual[a][b].celdaX;
d = actual[a][b].celdaY;
noStroke();
fill(255);
rect(c*w+1, d*w+1, w-1, w-1);
}
}
class Celda{
int celdaX, celdaY;
Celda(int celdaX, int celdaY){
this.celdaX = celdaX;
this.celdaY = celdaY;
}
}
我收到错误空指针异常
。
有人可以告诉我如何解决这个问题吗?
谢谢!
最佳答案
假设您的主要方法只是调用setup
,然后调用draw
:
pila.push(coordenada[c][d]); // c and d are 0, coordenada[0][0] is null
actual[a][b]=pila.pop(); // is null
c = actual[a][b].celdaX; // throws NullPointerException
您必须为 coordenada[0][0]
分配一个非空引用以避免异常。
关于java - 堆栈使用Processing(基于JAVA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28642618/