Boa tarde,
Estou a dias preso em um problema. Não estou conseguindo obter os valores gravados em uma lista, quando instanciados em outra classe.
Segue todo o meu fonte:
package conexao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Conexao {
public Connection getConection(){
try {
System.out.println("Status: Conectado");
return DriverManager.getConnection("jdbc:mysql://localhost/sorteio","root","vertrigo");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void desconecta() throws SQLException{
getConection().close();
}
}
package dados;
public class Numeros {
private int numero;
private int quantidade;
public int getNumero() {
return numero;
}
public void setNumero(int numero) {
this.numero = numero;
}
public int getQuantidade() {
return quantidade;
}
public void setQuantidade(int quantidade) {
this.quantidade = quantidade;
}
}
package modelo;
public class Rateio {
private int sorteio;
private String dataSorteio;
private String dezena1;
private String dezena2;
private String dezena3;
private String dezena4;
private String dezena5;
private String dezena6;
public int getSorteio() {
return sorteio;
}
public void setSorteio(int sorteio) {
this.sorteio = sorteio;
}
public String getDataSorteio() {
return dataSorteio;
}
public void setDataSorteio(String dataSorteio) {
this.dataSorteio = dataSorteio;
}
public String getDezena1() {
return dezena1;
}
public void setDezena1(String dezena1) {
this.dezena1 = dezena1;
}
public String getDezena2() {
return dezena2;
}
public void setDezena2(String dezena2) {
this.dezena2 = dezena2;
}
public String getDezena3() {
return dezena3;
}
public void setDezena3(String dezena3) {
this.dezena3 = dezena3;
}
public String getDezena4() {
return dezena4;
}
public void setDezena4(String dezena4) {
this.dezena4 = dezena4;
}
public String getDezena5() {
return dezena5;
}
public void setDezena5(String dezena5) {
this.dezena5 = dezena5;
}
public String getDezena6() {
return dezena6;
}
public void setDezena6(String dezena6) {
this.dezena6 = dezena6;
}
}
Eu importo um arquivo do Excel e adiciono os valores das celulas determinadas em uma lista. O método contaElementos irá me retornar a quantidade de repetições de um determinado número numa lista do tipo Numeros.
package dados;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import modelo.Rateio;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class Dados {
private Sheet sheet;
private Workbook wk;
private List<Rateio> listaRateio = new ArrayList<Rateio>();
public List<Rateio> listaRateioBase() throws IOException{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
int f = fc.showOpenDialog(null);
File file = fc.getSelectedFile();
if(f == JFileChooser.APPROVE_OPTION){
try {
wk = Workbook.getWorkbook(file);
sheet = wk.getSheet(0);
for(int i=5; i<sheet.getRows(); i++){
Rateio r = new Rateio();
Cell c = null;
c = sheet.getCell(0, i);
r.setSorteio(Integer.parseInt(c.getContents()));
c = sheet.getCell(1, i);
r.setDataSorteio(c.getContents());
c = sheet.getCell(2, i);
r.setDezena1(c.getContents());
c = sheet.getCell(3, i);
r.setDezena2(c.getContents());
c = sheet.getCell(4, i);
r.setDezena3(c.getContents());
c = sheet.getCell(5, i);
r.setDezena4(c.getContents());
c = sheet.getCell(6, i);
r.setDezena5(c.getContents());
c = sheet.getCell(7, i);
r.setDezena6(c.getContents());
listaRateio.add(r);
}
}
catch (BiffException e) {
JOptionPane.showMessageDialog(null, "Não foi possível abrir o arquivo "+file.getName()+". Formato não compatível.");
}
}
return listaRateio;
}
public List<Numeros> contaElementos(){ //Não estou conseguindo retornar os elementos guardados na lista em outra classe. Mas são listados perfeitamente nesta classe.
System.out.println("Contando...");
List<Numeros> numeros = new ArrayList<Numeros>();
Numeros n;
int cont = 0;
int vet[] = new int[60];
for(int i=0; i<vet.length; i++){
vet[i] = i+1;
}
for(int i=0; i<vet.length; i++){
for(Rateio lr : listaRateio){
if(vet[i] == Integer.parseInt(lr.getDezena1())
|| vet[i] == Integer.parseInt(lr.getDezena2())
|| vet[i] == Integer.parseInt(lr.getDezena3())
|| vet[i] == Integer.parseInt(lr.getDezena4())
|| vet[i] == Integer.parseInt(lr.getDezena5())
|| vet[i] == Integer.parseInt(lr.getDezena6()))
{
cont++;
}
}
n = new Numeros();
System.out.println("O numero "+vet[i]+" repetiu "+cont+" vezes");
n.setNumero(vet[i]);
n.setQuantidade(cont);
numeros.add(n);
cont=0;
}
return numeros; //Retorna os numeros repetidos e a quantidade de repetições.
}
}
package dao;
import dados.Dados;
import dados.Numeros;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import conexao.Conexao;
import modelo.Rateio;
public class DAO{
Connection conexao;
public void gravaBase() throws SQLException, IOException{ //Grava todos os valores guardados na lista no banco de dados.
Dados d = new Dados();
String sql;
conexao = new Conexao().getConection();
try{
System.out.println("Inserindo...");
for(Rateio rt : d.listaRateioBase()){
sql = "INSERT INTO sorteios VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement stmt = conexao.prepareStatement(sql);
stmt.setInt(1, rt.getSorteio());
stmt.setString(2, rt.getDataSorteio());
stmt.setString(3, rt.getDezena1());
stmt.setString(4, rt.getDezena2());
stmt.setString(5, rt.getDezena3());
stmt.setString(6, rt.getDezena4());
stmt.setString(7, rt.getDezena5());
stmt.setString(8, rt.getDezena6());
stmt.execute();
stmt.close();
}
System.out.println("Finalizado");
}finally{
conexao.close();
}
}
public List<Rateio> carregaSorteios() throws SQLException{ //Lista todos os valores da tabela no banco e retorna a lista.
conexao = new Conexao().getConection();
String sql = "SELECT * FROM sorteios";
PreparedStatement stmt = conexao.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
List<Rateio> listaRateios = new ArrayList<Rateio>();
System.out.println("Listando...");
while(rs.next()){
Rateio r = new Rateio();
r.setSorteio(rs.getInt("sorteiosId"));
r.setDataSorteio(rs.getString("sorteiosData"));
r.setDezena1(rs.getString("sorteiosDezena1"));
r.setDezena2(rs.getString("sorteiosDezena2"));
r.setDezena3(rs.getString("sorteiosDezena3"));
r.setDezena4(rs.getString("sorteiosDezena4"));
r.setDezena5(rs.getString("sorteiosDezena5"));
r.setDezena6(rs.getString("sorteiosDezena6"));
listaRateios.add(r);
}
System.out.println("Listados!");
rs.close();
stmt.close();
return listaRateios;
}
public void gravaElementos() throws SQLException{ //Quando eu vou inserir os valores no banco, o n.getNumero() vem com o índice, mas o n.getQuantidade() vem zerado.
conexao = new Conexao().getConection();
Dados d = new Dados();
try{
for(Numeros n : d.contaElementos()){ //Esse tipo de listagem está incorreto?
String sql = "INSERT INTO contabilizado (contabilizadoNumero, contabilizadoQuantidade) VALUES(?,?)";
PreparedStatement stmt = conexao.prepareStatement(sql);
stmt.setInt(1, n.getNumero());
stmt.setInt(2, n.getQuantidade());
System.out.println(n.getNumero());
System.out.println(n.getQuantidade());
stmt.execute();
stmt.close();
}
}finally{
conexao.close();
}
}
}
Como disse, quando eu tento fazer a listagem dos numeros que foram repetidos dentro da classe por outro método, os mesmos são listados.
Porém, quando tento fazer a listagem pelo método gravaElementos(), não consigo obter os valores guardados na lista.
Alguém pode me ajudar? Se possível, dando algumas dicas para melhorar o restante do código.
Desde já, obrigado!