Autor Tema: Java ArrayList que contiene objetos con atributos Suma de Elementos  (Leído 8467 veces)

LeonelCa

  • Sin experiencia
  • *
  • APR2.COM
  • Mensajes: 2
    • Ver Perfil
Hola buenas noches. Queria saber si me podian ayudar con el tema de arraylist en netbeans y es que tengo un arraylist guardado que contiene dos atributos uno con el nombre de una cuenta y otro con el saldo de la cuenta y tengo un JFrame en el que puedo selecionar un cuenta y agregarle un saldo...

Hasta ahi todo bien ya que todos los ingresos que hago los guarda pero separados todo por ejemplo cuando quiero ver el contenido el arraylist me aparecen todos los ingresos separado y las cuentas repetidas por ejemplo:

Hice un ingreso de dinero de 3000 y luego otro de 6000 me los muestra: Efectivo 3000, Efectivo 6000.

Y quisiera que si la cuentas son iguales, que automaticamente se sumen.

No se si puede hacer.... Agradeceria mucho me explicaran algun metodo para hacerlo o me explicaran si se puede o no.
« Última modificación: 29 de Marzo 2016, 14:55 por Alex Rodríguez »

Alex Rodríguez

  • Moderador Global
  • Experto
  • *******
  • Mensajes: 2050
    • Ver Perfil
Re:Suma de Elementos de un Arraylist
« Respuesta #1 en: 29 de Marzo 2016, 14:55 »
Hola Leonel no entiendo muy bien lo que quieres hacer.

Por lo que entiendo tienes un ArrayList de objetos tipo Cuenta, y cada objeto tiene un atributo nombre y otro atributo saldo.

Puedes hacer operaciones como recorrer el ArrayList y sumar todos los saldos si quieres.

Te recomiendo seguir este curso donde se explica todo lo relacionado: http://aprenderaprogramar.com/index.php?option=com_content&view=category&id=68&Itemid=188

También si haces alguna prueba de código y lo pegas como se explica en https://www.aprenderaprogramar.com/foros/index.php?topic=1460.0 podremos ver el código y darte una orientación

Saludos

LeonelCa

  • Sin experiencia
  • *
  • APR2.COM
  • Mensajes: 2
    • Ver Perfil
Re:Java ArrayList que contiene objetos con atributos Suma de Elementos
« Respuesta #2 en: 29 de Marzo 2016, 18:05 »
Código: [Seleccionar]

//Este es el codigo Principal
package proyectii;

import java.util.ArrayList;
import javax.swing.JOptionPane;


public class MenuPrinc extends javax.swing.JFrame {

   public static ArrayList<Ingresos> Ing = new ArrayList<Ingresos>();
   public static ArrayList<Gastos> Gas = new ArrayList<Gastos>();
   public static ArrayList<Cuentas> Cue = new ArrayList<Cuentas>();
   
    public MenuPrinc() {
        initComponents();
       
        }

    private void CatGastosActionPerformed(java.awt.event.ActionEvent evt) {                                         
      int Opc = JOptionPane.showConfirmDialog(this,"Ver Las Categoria de Gastos Incluidas","Categoria De Gastos",JOptionPane.YES_NO_OPTION);
        CategGastos CatG = new CategGastos();
        CatG.Gast = Gas;
        if (Opc==0){
          for(int i=0;i<Gas.size();i++){
          JOptionPane.showMessageDialog(null,"Categorias De Gastos\n"+"#Cuenta: "+Gas.get(i).getCodig()+"\nCategoria: "+Gas.get(i).getNombGast()+"\n");
      }
          CatG.setVisible(true);
           CatG.pack();
        }
           else{
           CatG.setVisible(true);
            CatG.pack();
         
      }     
    }                                         

    private void CatIngresActionPerformed(java.awt.event.ActionEvent evt) {                                         
        int Opc = JOptionPane.showConfirmDialog(this,"Ver Las Categoria de Ingresos Incluidas","Categoria De Ingresos",JOptionPane.YES_NO_OPTION);
          CategIngresos CatI = new CategIngresos();
          CatI.Ingr = Ing;
        if (Opc==0){
          for(int i=0;i<Ing.size();i++){
          JOptionPane.showMessageDialog(null,"Categorias De Ingreso\n"+"#Cuenta: "+Ing.get(i).getCodig()+"\nCategoria: "+Ing.get(i).getNombIngr()+"\n");
      }
          CatI.setVisible(true);
           CatI.pack();
        }
           else{
           CatI.setVisible(true);
            CatI.pack();
         
      }
    }                                         

    private void CuentasActionPerformed(java.awt.event.ActionEvent evt) {                                       
        int Opc = JOptionPane.showConfirmDialog(this,"Ver Las Categoria De Cuentas Incluidas","Categoria De Cuentas",JOptionPane.YES_NO_OPTION);
        CategCuentas CatC = new CategCuentas();
        CatC.Cuen = Cue;
        if (Opc==0){
          for(int i=0;i<Cue.size();i++){
          JOptionPane.showMessageDialog(null,"Categorias De Cuentas\n"+"#Cuenta: "+Cue.get(i).getCodig()+"\nCategoria: "+Cue.get(i).getNombCuent()+"\n");
      }
          CatC.setVisible(true);
          CatC.pack();
        }
           else{
           CatC.setVisible(true);
           CatC.pack();
      }
    }                                       

    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                 
       Ingresos I1 = new Ingresos("001","Salario");
      Ingresos I2 = new Ingresos("002","Remesas");
      Ingresos I3 = new Ingresos("003","Extras");
      Ing.add(I1);
      Ing.add(I2);
      Ing.add(I3);
           
      Gastos G1 = new Gastos("001","Alimentacion");
      Gastos G2 = new Gastos("002","Educacion");
      Gastos G3 = new Gastos("003","Salud");
      Gastos G4 = new Gastos("004","Transporte");
      Gas.add(G1);
      Gas.add(G2);
      Gas.add(G3);
      Gas.add(G4);
     
      Cuentas C1 = new Cuentas("001","Efectivo");
      Cuentas C2 = new Cuentas("002","Ficohsa");
      Cuentas C3 = new Cuentas("003","Promerica");
      Cuentas C4 = new Cuentas("004","Banco Atlantida");
      Cue.add(C1);
      Cue.add(C2);
      Cue.add(C3);
      Cue.add(C4);
     
    }                                 

    private void btnIngresosActionPerformed(java.awt.event.ActionEvent evt) {                                           
        MenuIngresos MI = new MenuIngresos();
        MI.setVisible(true);       
    }                                           

    private void btnGastosActionPerformed(java.awt.event.ActionEvent evt) {                                         
       MenuGastos MG = new MenuGastos();
       MG.setVisible(true);
    }                                         

    private void btnTransferActionPerformed(java.awt.event.ActionEvent evt) {                                           
        Transferencias MT = new Transferencias();
        MT.setVisible(true);
        String Cuent="";
        double NSald=0;
//Aqui es donde ocurre el problema
//Y si tengo un arraylist tipo Cuenta y correcto cada objeto lleva dos atributos
// Pero no se como hacer para sumarlos
        for(int x=0;x<MenuIngresos.Cuen.size();x++)
        for(int i=0;i<MenuIngresos.Cuen.size();i++){
            System.out.println("Cunta: "+MenuIngresos.Cuen.get(i).getNombCuent()+"\n Saldo: "+MenuIngresos.Cuen.get(i).getSaldo());
            if(MenuIngresos.Cuen.get(x).getNombCuent()==MenuIngresos.Cuen.get(i).getNombCuent()){
                MenuIngresos.Cuen.get(x).Saldo=MenuIngresos.Cuen.get(i).getSaldo();
                MenuIngresos.Cuen.get(x).Saldo+=MenuIngresos.Cuen.get(i).getSaldo();
            }
             System.out.println("Cunta: "+MenuIngresos.Cuen.get(x).getNombCuent()+"\n Saldo: "+MenuIngresos.Cuen.get(x).getSaldo());
          }
       
    }                                           

    public static void main(String args[]) {
     
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MenuPrinc().setVisible(true);
               
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JMenuItem CatGastos;
    private javax.swing.JMenuItem CatIngres;
    private javax.swing.JMenu Config;
    private javax.swing.JMenuItem Cuentas;
    private javax.swing.JMenuItem Presup;
    private javax.swing.JMenuItem RepGasCat;
    private javax.swing.JMenuItem RepGastTotCat;
    private javax.swing.JMenuItem RepGener;
    private javax.swing.JMenuItem RepIngCat;
    private javax.swing.JMenuItem RepIngCuent;
    private javax.swing.JMenuItem RepIngTotCat;
    private javax.swing.JMenuItem RepIngTotCunt;
    private javax.swing.JButton btnGastos;
    private javax.swing.JButton btnIngresos;
    private javax.swing.JButton btnTransfer;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    // End of variables declaration                   
}

Código: [Seleccionar]

//Realizar Ingresos
package proyectii;

import java.util.ArrayList;
import java.util.Date;

public class MenuIngresos extends javax.swing.JFrame {
   
    public String objectToString(Object o) {
        String st;
        st = (String) o;
        return st;
        }
     public String ConvString(Object Obj) {
     String Str="";
      if(Obj!=null){
      Str = Obj.toString();
       }
        return Str;
      }
   
 
   public ArrayList<Ingresos> Ingr= new ArrayList<Ingresos>();
    public static ArrayList<Cuentas> Cuen= new ArrayList<Cuentas>();
    public MenuIngresos() {
        initComponents();
    }

private void formWindowOpened(java.awt.event.WindowEvent evt) {                                 
     this.catIngre.removeAllItems();
     for(int i=0;i<MenuPrinc.Ing.size();i++){
       catIngre.addItem(MenuPrinc.Ing.get(i).getNombIngr());
       }
      this.catCuent.removeAllItems();
      for(int i=0;i<MenuPrinc.Cue.size();i++){
       catCuent.addItem(MenuPrinc.Cue.get(i).getNombCuent());
       } 
    }                                 

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {                                         
       this.dispose();
    }                                         

    private void btnGuardActionPerformed(java.awt.event.ActionEvent evt) {                                         
      Date F = new Date(Integer.parseInt(TxtDia.getText()),Integer.parseInt(TxtMes.getText()),Integer.parseInt(TxtAño.getText()));
      String CatIng = objectToString(this.catIngre.getSelectedItem());
      Double Cant = Double.parseDouble(TxtCantid.getText());
      String CatCu = objectToString(this.catCuent.getSelectedItem());
      String Coment = ConvString(TxtComent);
      Ingresos I = new Ingresos(F,CatIng,CatCu,Cant,Coment);
      Ingr.add(I);
      Cuentas C = new Cuentas(CatCu,Cant);       
      Cuen.add(C);
      this.dispose();
             
    }                                       

   public static void main(String args[]) {
 java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MenuIngresos().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JTextField TxtAño;
    private javax.swing.JTextField TxtCantid;
    private javax.swing.JTextField TxtComent;
    private javax.swing.JTextField TxtDia;
    private javax.swing.JTextField TxtMes;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnGuard;
    private javax.swing.JComboBox<String> catCuent;
    private javax.swing.JComboBox<String> catIngre;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    // End of variables declaration                   
}
 


Código: [Seleccionar]

//Poder Realizar Transferencias
package proyectii;

import java.util.ArrayList;
import java.util.Date;

public class Transferencias extends javax.swing.JFrame {
   
    public String objectToString(Object o) {
        String st;
        st = (String) o;
        return st;
        }
     public String ConvString(Object Obj) {
     String Str="";
      if(Obj!=null){
      Str = Obj.toString();
       }
        return Str;
      }
   
 
   public ArrayList<Cuentas> Cuent= new ArrayList<Cuentas>();
   
    public Transferencias() {
        initComponents();
    }

private void formWindowOpened(java.awt.event.WindowEvent evt) {                                 
     this.Cunta1.removeAllItems();
     for(int i=0;i<MenuPrinc.Cue.size();i++){
       Cunta1.addItem(MenuPrinc.Cue.get(i).getNombCuent());
       }
      this.Cuenta2.removeAllItems();
      for(int i=0;i<MenuPrinc.Cue.size();i++){
       Cuenta2.addItem(MenuPrinc.Cue.get(i).getNombCuent());
       } 
    }                                 

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {                                         
       this.dispose();
    }                                         

    private void btnGuardActionPerformed(java.awt.event.ActionEvent evt) {                                         
      Date F = new Date(Integer.parseInt(TxtDia.getText()),Integer.parseInt(TxtMes.getText()),Integer.parseInt(TxtAño.getText()));
      String Cuent1 = objectToString(this.Cunta1.getSelectedItem());
      Double Cant = Double.parseDouble(TxtCantid.getText());
      String Cuent2 = objectToString(this.Cuenta2.getSelectedItem());
      String Coment = ConvString(TxtComent);
      Cuentas C = new Cuentas(F,Cuent1,Cuent2,Cant,Coment);
      Cuent.add(C);
      this.dispose();
     
             
    }                                       

    private void Cunta1ActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
    }                                     

    private void Cuenta2ActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
    }                                       

    public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Transferencias().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel Cuenta1;
    private javax.swing.JComboBox<String> Cuenta2;
    private javax.swing.JLabel Cuenta3;
    private javax.swing.JLabel Cuenta4;
    private javax.swing.JComboBox<String> Cunta1;
    private javax.swing.JTextField TxtAño;
    private javax.swing.JTextField TxtCantid;
    private javax.swing.JTextField TxtComent;
    private javax.swing.JTextField TxtDia;
    private javax.swing.JTextField TxtMes;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnGuard;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    // End of variables declaration                   
}
 

Y las clases
 
Código: [Seleccionar]

package proyectii;

import java.util.Date;


public class Cuentas {
   String Codig;
   String NombCuent;
   double Saldo;
    Date Fecha;
    String Comen;
    String NombCuent2;
  public Cuentas() {
    }

    public Cuentas(String Codig, String NombCuent) {
        this.Codig = Codig;
        this.NombCuent = NombCuent;
    }

    public Cuentas(String NombCuent, double Saldo) {
        this.NombCuent = NombCuent;
        this.Saldo = Saldo;
    }
   
   

    public Cuentas(Date Fecha, String NombCuent, String NombCuent2, double Saldo, String Comen) {
        this.NombCuent = NombCuent;
        this.Saldo = Saldo;
        this.Fecha = Fecha;
        this.Comen = Comen;
        this.NombCuent2 = NombCuent2;
    }

    public double getSaldo() {
        return Saldo;
    }

    public void setSaldo(double Saldo) {
        this.Saldo = Saldo;
    }

    public Date getFecha() {
        return Fecha;
    }

    public void setFecha(Date Fecha) {
        this.Fecha = Fecha;
    }

    public String getComen() {
        return Comen;
    }

    public void setComen(String Comen) {
        this.Comen = Comen;
    }

    public String getNombCuent2() {
        return NombCuent2;
    }

    public void setNombCuent2(String NombCuent2) {
        this.NombCuent2 = NombCuent2;
    }
 

   
    public String getCodig() {
        return Codig;
    }

    public void setCodig(String Codigo) {
        this.Codig = Codigo;
    }

    public String getNombCuent() {
        return NombCuent;
    }

    public void setNombCuent(String NombCuent) {
        this.NombCuent = NombCuent;
    }
   
   
   
}
 

 
Código: [Seleccionar]

package proyectii;

import java.util.Date;


public class Ingresos extends Datos{
   String Codig;
    String NombIngr;
    double Saldo;
    Date Fecha;
    String Cuenta;
    String Comen;
    public Ingresos() {
    }

    public Ingresos(String NombIngr) {
        this.NombIngr = NombIngr;
    }

    public Ingresos(String Codig, String NombIngr) {
        this.Codig = Codig;
        this.NombIngr = NombIngr;
    }

     public Ingresos(Date Fecha, String NombIngr, String Cuenta, double Saldo, String Comen) {
        this.NombIngr = NombIngr;
        this.Saldo = Saldo;
        this.Fecha = Fecha;
        this.Cuenta = Cuenta;
        this.Comen = Comen;
    }

   
    public String getCodig() {
        return Codig;
    }

    public void setCodig(String Codig) {
        this.Codig = Codig;
    }


    public String getNombIngr() {
        return NombIngr;
    }

    public void setNombIngr(String NombIngr) {
        this.NombIngr = NombIngr;
    }
   @Override
    public String toString(){
        return NombIngr;
    }
    }

 

« Última modificación: 29 de Marzo 2016, 18:13 por LeonelCa »

Alex Rodríguez

  • Moderador Global
  • Experto
  • *******
  • Mensajes: 2050
    • Ver Perfil
Re:Java ArrayList que contiene objetos con atributos Suma de Elementos
« Respuesta #3 en: 31 de Marzo 2016, 14:39 »
¿En qué parte del código tienes los problemas? ¿Puedes poner un ejemplo con números reales donde se explique lo que debería hacerse? Por ejemplo: ejecutar tal clase, introducir como dato 20000, luego introducir 10000 luego... de modo que veamos un ejemplo real de lo que debería ocurrir.

 

Sobre la educación, sólo puedo decir que es el tema más importante en el que nosotros, como pueblo, debemos involucrarnos.

Abraham Lincoln (1808-1865) Presidente estadounidense.

aprenderaprogramar.com: Desde 2006 comprometidos con la didáctica y divulgación de la programación

Preguntas y respuestas

¿Cómo establecer o cambiar la imagen asociada (avatar) de usuario?
  1. Inicia sesión con tu nombre de usuario y contraseña.
  2. Pulsa en perfil --> perfil del foro
  3. Elige la imagen personalizada que quieras usar. Puedes escogerla de una galería de imágenes o subirla desde tu ordenador.
  4. En la parte final de la página pulsa el botón "cambiar perfil".