3
I have the Door, Building and Main classes:
public class Porta {
boolean aberta;
String cor;
double dimensaoX, dimensaoY, dimensaoZ;
void abre() {
this.aberta = true;
}
void fecha() {
this.aberta = false;
}
void pinta(String cor) {
this.cor = cor;
}
boolean estaAberta() {
boolean estaAberta = false;
if(aberta == true) estaAberta = true;
return estaAberta;
}
public class Edificio {
String cor;
int totalDePortas;
int totalDeAndares;
Porta portas[];
int elementos = 0;
void pinta(String cor) {
this.cor = cor;
}
int quantasPortasEstaoAbertas() {
int qtdPortasAbertas=0;
for(int i=0; i<this.portas.length; i++) {
if(portas[i].aberta == true) qtdPortasAbertas++;
}
return qtdPortasAbertas;
}
void adicionaPorta(Porta porta) {
for(int i=0; i<this.portas.length; i++) {
if(this.portas[i] == null) this.portas[i] = porta;
}
}
int totalDePortas() {
int totalPortas=0;
for(int i=0; i<this.portas.length; i++) {
if(this.portas[i] != null) totalPortas++;
}
return totalPortas++;
}
void adicionaAndar() {
this.totalDeAndares = totalDeAndares+=1;
}
int totalDeAndares() {
return this.totalDeAndares;
}
public class Exer05 {
public static void main(String[] args) {
//A
Porta p1 = new Porta();
p1.abre();
p1.fecha();
p1.pinta("Azul");
p1.pinta("Verde");
p1.dimensaoX = 1.80;
p1.dimensaoY = 1.00;
p1.dimensaoZ = 1.80;
if(p1.estaAberta() == true) System.out.println("A porta"
+ " está aberta");
else System.out.println("A porta está fechada");
//B
Edificio ed = new Edificio();
Porta p2 = new Porta();
p1.fecha();
ed.adicionaPorta(p2);
Porta p3 = new Porta();
p1.abre();
ed.adicionaPorta(p3);
Porta p4 = new Porta();
p1.abre();
ed.adicionaPorta(p4);
Porta p5 = new Porta();
p1.abre();
ed.adicionaPorta(p5);
Porta p6 = new Porta();
p1.abre();
ed.adicionaPorta(p6);
Porta p7 = new Porta();
p1.fecha();
ed.adicionaPorta(p7);
ed.quantasPortasEstaoAbertas();
}
It turns out that when I call the added methodPort() in the main class, the following error happens:
Exception in thread "main" java.lang.NullPointerException
at br.edu.utfpr.exer05.Edificio.adicionaPorta(Edificio.java:23)
at br.edu.utfpr.exer05.Exer05.main(Exer05.java:24)
How to solve?
Thank you
Hello, I’m also new to programming but you have to, in the method where you put how many doors you have to put +1 in the cycle right in front of where the method of seeing the string length is, sorry if n can explain well but I prefer to speak English :p
– L3n
Already solved, I used the collection Arraylist for this.
– rodrigom