Duvida sobre ArrayList

3 respostas
W

Olá estou precisando muito de ajuda para fazer um programa de video locadora em java, as funções que tenho que ter são:
1 - Cadastro de Clientes;
2 - Cadastro de Filmes;
3 - Exclusão de Cliente;
4 - Pesquisa de Cliente;
5 - Salvar e Sair;

O cadastro de cliente eu consegui e fazer ele gravar em arquivo .txt mas não o de filmes, mas não estou conseguindo fazer ele excluir, alterar ou pesquisar se alguém poder me ajudar estou tendo um problema na metodo init().

import java.util.List;
import java.util.Scanner;

import persistencia.DAOException;
import persistencia.DAOGenerico;

public class Sistema {

    private List<Cliente> listaCliente;
    private List<Filmes> listaFilmes;
    protected static final int TELA_PRINCIPAL = 0;
    protected static final int TELA_CADASTRO_CLIENTE = 1;
    protected static final int TELA_ALTERACAO_CLIENTE = 2;
    protected static final int TELA_EXCLUSAO_CLIENTE = 3;
    protected static final int TELA_ADICIONAR_CLIENTE = 4;
    protected static final int TELA_PESQUISA_CLIENTE = 5;
    protected static final int TELA_CADASTRO_FILME = 6;

    protected static final int LENDO_OPCAO = 0;
    protected static final int LENDO_DADOS = 1;

    public static void main(String[] args) throws DAOException {
        Sistema sistema = new Sistema();
        sistema.init();
        sistema.run();
    }

    public void init() throws DAOException {
        // gravação das entidades em disco.
        DAOGenerico dao = new DAOGenerico();

        // leitura de arquivo e criação da lista de entidades.
        listaCliente = dao.lerEntidadesDeArquivo("cadastro_cliente.txt", Cliente.class);
        listaFilmes = dao.lerEntidadesDeArquivo("cadastro_filmes.txt", Filmes.class);

    }

    protected int telaAtual;
    protected int status;
    protected boolean sistemaOperante;
    protected Scanner scanner;

    public Sistema() {
        this.scanner = new Scanner(System.in);
        this.telaAtual = TELA_PRINCIPAL;
        this.status = LENDO_OPCAO;
        this.sistemaOperante = true;
    }

    public void mostrarTela() throws DAOException {
        switch (this.telaAtual) {
            case TELA_PRINCIPAL:
                mostrarTelaPrincipal();
                break;
            case TELA_CADASTRO_CLIENTE:
                mostrarTelaCadastroCliente();
                break;
            case TELA_ALTERACAO_CLIENTE:
                mostrarAlteracaoCadastroCliente();
                break;
            case TELA_EXCLUSAO_CLIENTE:
                mostrarExclusaoCadastroCliente();
                break;
            case TELA_ADICIONAR_CLIENTE:
                mostrarTelaAdicionarCliente();
                break;
            case TELA_PESQUISA_CLIENTE:
                mostrarTelaPesquisaCliente();
                break;
            case TELA_CADASTRO_FILME:
                mostrarTelaCadastroFilme();
                break;

            default:
                mostrarTelaPrincipal();
        }
    }

    private void mostrarTelaCadastroCliente() {
        System.out.println("** Cadastro de clientes **");
        System.out.println();
        System.out.println("Escolha uma opção opção:");
        System.out.println("1 - Adicionar cliente");
        System.out.println("2 - Alterar de Cliente");
        System.out.println("\n Digite 3 para retornar a tela anterior:");

    }

    private void mostrarTelaAdicionarCliente() {
        System.out.println("** Adição de clientes **");

        System.out.println("\n Digite a matricula do Cliente:");
        int id_cliente = scanner.nextInt();
        System.out.println("\n Digite o nome:");
        String nome = scanner.next();
        System.out.println("\n Digite o CPF:");
        int cpf = scanner.nextInt();
        System.out.println("\n Digite o telefone: ");
        int telefone = scanner.nextInt();
        System.out.println("\n Digite 1 para retornar a tela anterior:");

        Cliente novo = new Cliente();
        novo.setId_cliente(id_cliente);
        novo.setNome(nome);
        novo.setCpf(cpf);
        novo.setTelefone(telefone);
        listaCliente.add(novo);
    }

    private void mostrarTelaCadastroFilme() {
        System.out.println("** Cadastro de Filmes **");

        System.out.println("\n Digite a id do Filme:");
        int id_filme = scanner.nextInt();
        System.out.println("\n Digite o nome:");
        String nome = scanner.next();
        System.out.println("\n Digite a Categoria:");
        String categoria = scanner.next();
        System.out.println("\n Digite o Ano de Lançamento: ");
        int lancamento_ano = scanner.nextInt();
        System.out.println("\n Digite 1 para retornar a tela anterior:");

        Filmes novo = new Filmes();
        novo.setId_filme(id_filme);
        novo.setNome(nome);
        novo.setCategoria(categoria);
        novo.setLancamento_ano(lancamento_ano);
        listaFilmes.add(novo);
    }

    private void mostrarAlteracaoCadastroCliente() {
        System.out.println("** Alteração de clientes **");

        System.out.println("\n Digite a matricula do Cliente:");
        int id_cliente = scanner.nextInt();
        System.out.println("\n Digite o nome:");
        String nome = scanner.next();
        System.out.println("\n Digite o CPF:");
        int cpf = scanner.nextInt();
        System.out.println("\n Digite o telefone: ");
        int telefone = scanner.nextInt();
        System.out.println("\n Digite 1 para retornar a tela anterior:");

        Cliente novo = new Cliente();
        novo.setId_cliente(id_cliente);
        novo.setNome(nome);
        novo.setCpf(cpf);
        novo.setTelefone(telefone);
        listaCliente.remove(novo);

    }

    private void mostrarExclusaoCadastroCliente() {
        System.out.println("** Exclusão de clientes **");

        System.out.println("\n Digite a matricula do Cliente:");
        int id_cliente = scanner.nextInt();
        System.out.println("\n Digite o nome:");
        String nome = scanner.next();
        System.out.println("\n Digite o CPF:");
        int cpf = scanner.nextInt();
        System.out.println("\n Digite o telefone: ");
        int telefone = scanner.nextInt();
        System.out.println("\n Digite 1 para retornar a tela anterior:");

        Cliente novo = new Cliente();
        novo.setId_cliente(id_cliente);
        novo.setNome(nome);
        novo.setCpf(cpf);
        novo.setTelefone(telefone);
        listaCliente.remove(novo);
    }

    private void mostrarTelaPesquisaCliente() throws DAOException {
        System.out.println("** Pesquisa de clientes **");

        System.out.println("\n Digite a matricula do Cliente:");
        int id_cliente = scanner.nextInt();
        System.out.println("\n Digite o nome:");

        DAOGenerico dao = new DAOGenerico();
        listaCliente = dao.lerEntidadesDeArquivo("cadastro.txt", Cliente.class);
        if (listaCliente.contains(id_cliente))
            System.out.println("Está lá!");
        else
            System.out.println("Não está lá!");

        System.out.println("\n Digite 1 para retornar a tela anterior:");

    }

    private void mostrarTelaPrincipal() {
        System.out.println("** Sistema controle de Video Locadora **");
        System.out.println();
        System.out.println("Escolha uma opção opção:");
        System.out.println("1 - Cadastro de Cliente");
        System.out.println("2 - Cadastro de Filmes");
        System.out.println("3 - Exclusão de Cliente");
        System.out.println("4 - Pesquisa de Cliente");
        System.out.println("5 - Sair e Salvar");
    }

    private void processaDado(String value) {
        // TODO Auto-generated method stub

    }

    private void processaOpcao(int opcao) throws DAOException {
        switch (telaAtual) {
            case TELA_PRINCIPAL:
                switch (opcao) {
                    case 1:
                        telaAtual = TELA_CADASTRO_CLIENTE;
                        break;
                    case 2:
                        telaAtual = TELA_CADASTRO_FILME;
                        break;
                    case 3:
                        telaAtual = TELA_EXCLUSAO_CLIENTE;
                        break;
                    case 4:
                        telaAtual = TELA_PESQUISA_CLIENTE;
                        break;
                    case 5:
                        DAOGenerico dao = new DAOGenerico();
                        dao.salvarEntidadeEmArquivo("cadastro_filmes.txt", listaCliente);
                        dao.salvarEntidadeEmArquivo("cadastro_cliente.txt", listaFilmes);
                        this.sistemaOperante = false;
                        break;
                }
                break;
            case TELA_CADASTRO_CLIENTE:
                switch (opcao) {
                    case 1:
                        telaAtual = TELA_ADICIONAR_CLIENTE;
                        break;
                    case 2:
                        telaAtual = TELA_ALTERACAO_CLIENTE;
                        break;
                    case 3:
                        telaAtual = TELA_PRINCIPAL;
                        break;
                }
                break;

            case TELA_ALTERACAO_CLIENTE:
                switch (opcao) {
                    case 1:
                        telaAtual = TELA_ALTERACAO_CLIENTE;
                        break;
                    case 2:
                        telaAtual = TELA_CADASTRO_CLIENTE;
                        break;

                }
                break;
            case TELA_EXCLUSAO_CLIENTE:
                switch (opcao) {
                    case 1:
                        telaAtual = TELA_PRINCIPAL;
                        break;

                }
                break;
            case TELA_ADICIONAR_CLIENTE:
                switch (opcao) {
                    case 1:
                        telaAtual = TELA_PRINCIPAL;
                        break;

                }
                break;
            case TELA_PESQUISA_CLIENTE:
                switch (opcao) {
                    case 1:
                        telaAtual = TELA_PRINCIPAL;
                        break;

                }
                break;
        }
    }

    public void run() throws DAOException {
        String value;
        int opcao;
        do {
            mostrarTela();
            if (this.status == LENDO_OPCAO) {
                opcao = scanner.nextInt();
                processaOpcao(opcao);
            } else if (this.status == LENDO_DADOS) {
                value = scanner.next();
                processaDado(value);
            }
        } while (this.sistemaOperante);
    }

}
import persistencia.DAOException;
import persistencia.DAOGenerico;

public class Cliente {

    private int id_cliente;
    private String nome;
    private int cpf;
    private int telefone;

    public int getId_cliente() {
        return id_cliente;
    }

    public void setId_cliente(int id_cliente) {
        this.id_cliente = id_cliente;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public int getCpf() {
        return cpf;
    }

    public void setCpf(int cpf) {
        this.cpf = cpf;
    }

    public int getTelefone() {
        return telefone;
    }

    public void setTelefone(int telefone) {
        this.telefone = telefone;
    }

}
public class Filmes {

    private int id_filme;
    private String nome;
    private String categoria;
    private int lancamento_ano;

    public int getId_filme() {
        return id_filme;
    }

    public void setId_filme(int id_filme) {
        this.id_filme = id_filme;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getCategoria() {
        return categoria;
    }

    public void setCategoria(String categoria) {
        this.categoria = categoria;
    }

    public int isLancamento_ano() {
        return lancamento_ano;
    }

    public void setLancamento_ano(int lancamento_ano) {
        this.lancamento_ano = lancamento_ano;
    }

}
package persistencia;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConstructorUtils;

/**
 * DAO usado para persistência de objetos em disco. Tem a característica de ser
 * genérico, ou seja, trabalhar com qualquer classe que seja um JavaBean.
 */
public class DAOGenerico {

    /**
     * Cria a descrição da entidade em formato CSV.
     * 
     * @param atributos
     * @return
     */
    private String criarEntradaArquivo(Map atributos) {
        StringBuffer descricao = new StringBuffer();
        for (Object key : atributos.keySet()) {
            descricao.append(key.toString());
            descricao.append("->");
            descricao.append(atributos.get(key));
            descricao.append(';');
        }

        // retorna a descrição da entidade.
        return descricao.toString();
    }

    /**
     * Lê um arquivo e gera a lista de entidades associadas.
     * 
     * @param <T>
     *            Tipo (classe) das entidades.
     * @param arquivo
     *            Nome do arquivo que contém os dados.
     * @param T
     *            Tipo da entidade.
     * @return Lista com entidades criadas.
     * @throws DAOException
     *             se algum erro ocorrer durante o processo.
     */
    public <T> List<T> lerEntidadesDeArquivo(String arquivo, Class T) throws DAOException {
        try {
            ArrayList<T> listaObjetos = new ArrayList<T>();
            FileReader fr = new FileReader(arquivo);
            BufferedReader br = new BufferedReader(fr);

            String line = br.readLine();
            while (line != null) {
                System.out.println(line);
                Map<String, String> atributos = new HashMap<String, String>();
                String[] campos = line.split(";");
                for (String campo : campos) {
                    if (!"".equals(campo)) {
                        String valor[] = campo.split("->");
                        atributos.put(valor[0], valor[1]);
                    }
                }
                T bean = (T) ConstructorUtils.invokeConstructor(T, new Object[0]);
                BeanUtils.populate(bean, atributos);
                listaObjetos.add(bean);
                line = br.readLine();
            }

            // retorna a lista de objetos lidos.
            return listaObjetos;
        } catch (Exception e) {
            throw new DAOException("Erro ao ler entidades do arquivo.", e);
        }
    }

    /**
     * Grava uma lista de entidades em um determinado arquivo.
     * 
     * @param <T>
     *            O Tipo (classe) da entidade.
     * @param arquivo
     *            Nome do arquivo onde as informações serão gravadas.
     * @param entidades
     *            Lista com as entidades que serão gravadas.
     * @throws DAOException
     *             se algum problema ocorrer durante o processo de gravação.
     */
    public <T> void salvarEntidadeEmArquivo(String arquivo, List<T> entidades) throws DAOException {
        try {
            FileWriter fw = new FileWriter(arquivo);

            // processa as entidades
            for (T objeto : entidades) {
                Map atributos;
                atributos = BeanUtils.describe(objeto);
                String descricaoObjeto = criarEntradaArquivo(atributos);
                fw.write(descricaoObjeto);
                fw.write("\n");
            }

            // fecha o arquivo.
            fw.flush();
            fw.close();
        } catch (Exception e) {
            throw new DAOException("Erro ao gravar os dados das entidades.", e);
        }
    }
}
package persistencia;

public class DAOException extends Exception {

    public DAOException() {
    }

    public DAOException(String arg0) {
        super(arg0);
    }

    public DAOException(String arg0, Throwable arg1) {
        super(arg0, arg1);
    }

    public DAOException(Throwable arg0) {
        super(arg0);
    }

}

3 Respostas

LPJava

olha se vc está usando o arraylist para encontrar o elemento é bem simples

for(String lista : arraylist){
if(lista.equals("lpjava"){
System.out.println(" :D  "); 
}
}

no equals vc vai testar o valor diigtado para pesquisa…

Estou usando o for aprimorado para percorrer toda a lista, agora tem um detalhe, se tiver nome repetido ai vai dar merda. É bom que sua lista nao tenha elementos repetidos e nesse caso nao seria do tipo ArrayList.

W

Valeu mas vc sabe como posso aplicar nesse codigo, e como posso excluir ou alterar um item da lista?
Estou tentando fazer uma pesquisa na lista mas sempre me retorna que o valor não esta lá...

private void mostrarTelaPesquisaCliente() throws DAOException {

        System.out.println("** Pesquisa de clientes **");

        System.out.println("\n Digite a matricula do Cliente:");
        String id_cliente = scanner.next();

        if (listaCliente.equals(id_cliente)) {
            System.out.println("Está cadastrado!");
        } else {
            System.out.println("Não está cadastrado!");
        }

        System.out.println("\n Digite 1 para retornar a tela anterior:");

    }
W

Se alguém puder me ajudar nesse caso descrito acima fico muito grato, pois esse projeto eu tenho que entregar até segunda-feira…

Criado 7 de junho de 2009
Ultima resposta 7 de jun. de 2009
Respostas 3
Participantes 2