Question:
I have a problem to implement this code, I can't insert the data in the Arraylist.
public class Principal {
public static void main(String[] args) {
Faltas faltas = new Faltas();
faltas.inserirDados(111,3,5);
for(int j=0;j<faltas.size();j++){
System.out.println(faltas.get(j).getDados());
}
}
}
import java.util.ArrayList;
import java.util.List;
public class Faltas {
int matricula;
int mes;
int dia;
ArrayList<Faltas> faltas = new ArrayList();
public Faltas(int matricula, int mes, int dia) {
this.matricula = matricula;
this.mes = mes;
this.dia = dia;
}
public void inserirDados(int matricula,int mes, int dia) {
faltas.addAll(matricula,mes,dia);
}
public String getDados(){
return "matricula: "+this.matricula+
"\nMes: "+this.mes+
"\nDia: "+this.dia+
"\n";
}
}
Compilation error:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The constructor Faltas() is undefined
The method size() is undefined for the type Faltas
The method get(int) is undefined for the type Faltas
at TesteArray.Principal.main(Principal.java:9)
Answer:
I suggest taking a look at your object-oriented concepts. The fault has to be created as a simple object and the list is a union of several faults and is outside the base class. Below is the ideal form.
import java.util.ArrayList;
public class Principal {
public static void main(String[] args) {
ArrayList<Falta> faltas = new ArrayList();
faltas.add(new Falta(111,3,5));
for(int j=0;j<faltas.size();j++){
System.out.println(faltas.get(j).getDados());
}
}
}
public class Falta {
int matricula;
int mes;
int dia;
public Falta(int matricula, int mes, int dia) {
this.matricula = matricula;
this.mes = mes;
this.dia = dia;
}
public String getDados(){
return "matricula: "+this.matricula+
"\nMes: "+this.mes+
"\nDia: "+this.dia+
"\n";
}
}