elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Estamos en la red social de Mastodon


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  Ayuda, obtener datos de Objetos en ArrayList
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] 2 Ir Abajo Respuesta Imprimir
Autor Tema: Ayuda, obtener datos de Objetos en ArrayList  (Leído 7,576 veces)
touchi

Desconectado Desconectado

Mensajes: 8


Ver Perfil
Ayuda, obtener datos de Objetos en ArrayList
« en: 27 Febrero 2015, 21:25 pm »

Tengo que realizar un programa el cual Cargue artículos, muestre todos los artículos cargado y luego en otra ventana de consulta muestre:

cantidad de productos de cada tipo.
total de dinero en artículos.
porcentaje de artículos de tipo 2.
Y articulo con el precio mas elevado.

Ya realice la carga de artículos y la otra pantalla que muestra todos los artículos cargados.
Mi problema es la ventana de consulta que muestra específicamente ciertos datos.


Este es mi código, si alguien me puede dar una mano por favor. Tengo un examen pronto y la verdad que eso me esta complicando la vida.

https://www.mediafire.com/?6tzn3g25uhv07fu



Main Class
Código
  1. ]public class Clase14Quiosco {
  2.  
  3.  
  4.    public static void main(String[] args) {
  5.        MenuPrincipal v = new MenuPrincipal();
  6.        v.setVisible(true);
  7.    }
  8.  
  9. }
  10.  
  11.  



MenuPrincipal class
Código
  1. import java.util.ArrayList;
  2. import javax.swing.JOptionPane;
  3.  
  4.  
  5. public class MenuPrincipal extends javax.swing.JFrame {
  6.  
  7.    private ArrayList<Articulo> listaArticulos;
  8.  
  9.  
  10.    public MenuPrincipal() {
  11.        initComponents();
  12.        listaArticulos = new ArrayList<>();
  13.    }
  14.  
  15.  
  16.    private void initComponents() {
  17.  
  18.        jMenuBar1 = new javax.swing.JMenuBar();
  19.        jMenu1 = new javax.swing.JMenu();
  20.        jMenuItem1 = new javax.swing.JMenuItem();
  21.        jMenu2 = new javax.swing.JMenu();
  22.        jMenuItem2 = new javax.swing.JMenuItem();
  23.  
  24.        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  25.  
  26.        jMenu1.setText("Articulos");
  27.        jMenu1.addActionListener(new java.awt.event.ActionListener() {
  28.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  29.                jMenu1ActionPerformed(evt);
  30.            }
  31.        });
  32.  
  33.        jMenuItem1.setText("Alta");
  34.        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
  35.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  36.                jMenuItem1ActionPerformed(evt);
  37.            }
  38.        });
  39.        jMenu1.add(jMenuItem1);
  40.  
  41.        jMenuBar1.add(jMenu1);
  42.  
  43.        jMenu2.setText("Reportes");
  44.  
  45.        jMenuItem2.setText("Listado");
  46.        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
  47.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  48.                jMenuItem2ActionPerformed(evt);
  49.            }
  50.        });
  51.        jMenu2.add(jMenuItem2);
  52.  
  53.        jMenuBar1.add(jMenu2);
  54.  
  55.        setJMenuBar(jMenuBar1);
  56.  
  57.        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  58.        getContentPane().setLayout(layout);
  59.        layout.setHorizontalGroup(
  60.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  61.            .addGap(0, 400, Short.MAX_VALUE)
  62.        );
  63.        layout.setVerticalGroup(
  64.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  65.            .addGap(0, 279, Short.MAX_VALUE)
  66.        );
  67.  
  68.        pack();
  69.    }// </editor-fold>                        
  70.  
  71.    private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
  72.  
  73.    }                                      
  74.  
  75.    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                          
  76.        AltaArticulo v = new AltaArticulo(listaArticulos);
  77.        v.setVisible(true);
  78.    }                                          
  79.  
  80.    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {                                          
  81.        ConsultaArticulos v = new ConsultaArticulos(listaArticulos);
  82.        v.setVisible(true);
  83.    }                                          
  84.  
  85.  
  86.    // Variables declaration - do not modify                    
  87.    private javax.swing.JMenu jMenu1;
  88.    private javax.swing.JMenu jMenu2;
  89.    private javax.swing.JMenuBar jMenuBar1;
  90.    private javax.swing.JMenuItem jMenuItem1;
  91.    private javax.swing.JMenuItem jMenuItem2;
  92.    // End of variables declaration                  
  93. }
  94.  
  95.  


AltaArticulo class
Código
  1. import java.util.ArrayList;
  2. import javax.swing.JOptionPane;
  3.  
  4.  
  5. public class AltaArticulo extends javax.swing.JFrame {
  6.  
  7.    private ArrayList<Articulo> listaArticulos;
  8.  
  9.    public AltaArticulo() {
  10.        initComponents();
  11.    }
  12.  
  13.    public AltaArticulo(ArrayList<Articulo> listaArticulos) {
  14.        initComponents();
  15.        this.listaArticulos = listaArticulos;
  16.    }
  17.  
  18.  
  19.    private void initComponents() {
  20.  
  21.        jLabel1 = new javax.swing.JLabel();
  22.        jLabel2 = new javax.swing.JLabel();
  23.        jLabel3 = new javax.swing.JLabel();
  24.        jLabel4 = new javax.swing.JLabel();
  25.        jLabel5 = new javax.swing.JLabel();
  26.        jLabel6 = new javax.swing.JLabel();
  27.        txtCodigo = new javax.swing.JTextField();
  28.        txtNombre = new javax.swing.JTextField();
  29.        txtPrecio = new javax.swing.JTextField();
  30.        txtStockActual = new javax.swing.JTextField();
  31.        txtStockMinimo = new javax.swing.JTextField();
  32.        cboCategoria = new javax.swing.JComboBox();
  33.        btnAgregar = new javax.swing.JButton();
  34.  
  35.        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
  36.  
  37.        jLabel1.setText("Codigo");
  38.  
  39.        jLabel2.setText("Nombre");
  40.  
  41.        jLabel3.setText("Precio");
  42.  
  43.        jLabel4.setText("Stock actual");
  44.  
  45.        jLabel5.setText("Stock mínimo");
  46.  
  47.        jLabel6.setText("Categoria");
  48.  
  49.        txtCodigo.addActionListener(new java.awt.event.ActionListener() {
  50.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  51.                txtCodigoActionPerformed(evt);
  52.            }
  53.        });
  54.  
  55.        cboCategoria.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Almacen", "Perfumeria", "Otros" }));
  56.  
  57.        btnAgregar.setText("Agregar");
  58.        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
  59.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  60.                btnAgregarActionPerformed(evt);
  61.            }
  62.        });
  63.  
  64.        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  65.        getContentPane().setLayout(layout);
  66.        layout.setHorizontalGroup(
  67.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  68.            .addGroup(layout.createSequentialGroup()
  69.                .addGap(46, 46, 46)
  70.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
  71.                    .addComponent(jLabel2)
  72.                    .addComponent(jLabel1)
  73.                    .addComponent(jLabel6)
  74.                    .addComponent(jLabel5)
  75.                    .addComponent(jLabel3)
  76.                    .addComponent(jLabel4))
  77.                .addGap(18, 18, 18)
  78.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
  79.                    .addComponent(btnAgregar)
  80.                    .addComponent(cboCategoria, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  81.                    .addComponent(txtCodigo)
  82.                    .addComponent(txtNombre)
  83.                    .addComponent(txtPrecio)
  84.                    .addComponent(txtStockActual)
  85.                    .addComponent(txtStockMinimo))
  86.                .addContainerGap(41, Short.MAX_VALUE))
  87.        );
  88.        layout.setVerticalGroup(
  89.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  90.            .addGroup(layout.createSequentialGroup()
  91.                .addGap(26, 26, 26)
  92.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  93.                    .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  94.                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
  95.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  96.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  97.                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  98.                    .addComponent(jLabel2))
  99.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  100.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  101.                    .addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  102.                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
  103.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  104.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  105.                    .addComponent(txtStockActual, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  106.                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
  107.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  108.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  109.                    .addComponent(txtStockMinimo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  110.                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
  111.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  112.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  113.                    .addComponent(cboCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  114.                    .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
  115.                .addGap(18, 18, 18)
  116.                .addComponent(btnAgregar)
  117.                .addContainerGap(24, Short.MAX_VALUE))
  118.        );
  119.  
  120.        pack();
  121.    }// </editor-fold>                        
  122.  
  123.    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {                                          
  124.        int codigo = Integer.parseInt(txtCodigo.getText());
  125.        String nombre = txtNombre.getText();
  126.        float precio = Float.parseFloat(txtPrecio.getText());
  127.        int stockActual = Integer.parseInt(txtStockActual.getText());
  128.        int stockMinimo = Integer.parseInt(txtStockMinimo.getText());
  129.        int categoria = cboCategoria.getSelectedIndex()+1;
  130.  
  131.        Articulo nuevo = new Articulo();
  132.  
  133.        nuevo.setCodigo(codigo);
  134.        nuevo.setNombre(nombre);
  135.        nuevo.setPrecio(precio);
  136.        nuevo.setStockActual(stockActual);
  137.        nuevo.setStockMinimo(stockMinimo);
  138.        nuevo.setCategoria(categoria);
  139.  
  140.        listaArticulos.add(nuevo);
  141.  
  142.        JOptionPane.showMessageDialog(this, listaArticulos.toString());
  143.    }                                          
  144.  
  145.    private void txtCodigoActionPerformed(java.awt.event.ActionEvent evt) {                                          
  146.        // TODO add your handling code here:
  147.    }                                        
  148.  
  149.  
  150.    public static void main(String args[]) {
  151.  
  152.  
  153.        try {
  154.            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  155.                if ("Nimbus".equals(info.getName())) {
  156.                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
  157.                    break;
  158.                }
  159.            }
  160.        } catch (ClassNotFoundException ex) {
  161.            java.util.logging.Logger.getLogger(AltaArticulo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  162.        } catch (InstantiationException ex) {
  163.            java.util.logging.Logger.getLogger(AltaArticulo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  164.        } catch (IllegalAccessException ex) {
  165.            java.util.logging.Logger.getLogger(AltaArticulo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  166.        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  167.            java.util.logging.Logger.getLogger(AltaArticulo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  168.        }
  169.        //</editor-fold>
  170.  
  171.  
  172.        java.awt.EventQueue.invokeLater(new Runnable() {
  173.            public void run() {
  174.                new AltaArticulo().setVisible(true);
  175.            }
  176.        });
  177.    }
  178.  
  179.    // Variables declaration - do not modify                    
  180.    private javax.swing.JButton btnAgregar;
  181.    private javax.swing.JComboBox cboCategoria;
  182.    private javax.swing.JLabel jLabel1;
  183.    private javax.swing.JLabel jLabel2;
  184.    private javax.swing.JLabel jLabel3;
  185.    private javax.swing.JLabel jLabel4;
  186.    private javax.swing.JLabel jLabel5;
  187.    private javax.swing.JLabel jLabel6;
  188.    private javax.swing.JTextField txtCodigo;
  189.    private javax.swing.JTextField txtNombre;
  190.    private javax.swing.JTextField txtPrecio;
  191.    private javax.swing.JTextField txtStockActual;
  192.    private javax.swing.JTextField txtStockMinimo;
  193.    // End of variables declaration                  
  194. }
  195.  
  196.  




ConsultaArticulos class

Código
  1. import java.util.ArrayList;
  2.  
  3. public class ConsultaArticulos extends javax.swing.JFrame {
  4.  
  5.  
  6.    public ConsultaArticulos() {
  7.        initComponents();
  8.    }
  9.  
  10.    public ConsultaArticulos(ArrayList<Articulo> listaArticulos) {
  11.        initComponents();
  12.        lstArticulos.setListData(listaArticulos.toArray());
  13.    }
  14.  
  15.    private void initComponents() {
  16.  
  17.        jScrollPane1 = new javax.swing.JScrollPane();
  18.        lstArticulos = new javax.swing.JList();
  19.  
  20.        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
  21.  
  22.        jScrollPane1.setViewportView(lstArticulos);
  23.  
  24.        getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
  25.  
  26.        pack();
  27.    }// </editor-fold>                        
  28.  
  29.  
  30.    public static void main(String args[]) {
  31.  
  32.        try {
  33.            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  34.                if ("Nimbus".equals(info.getName())) {
  35.                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
  36.                    break;
  37.                }
  38.            }
  39.        } catch (ClassNotFoundException ex) {
  40.            java.util.logging.Logger.getLogger(ConsultaArticulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  41.        } catch (InstantiationException ex) {
  42.            java.util.logging.Logger.getLogger(ConsultaArticulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  43.        } catch (IllegalAccessException ex) {
  44.            java.util.logging.Logger.getLogger(ConsultaArticulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  45.        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  46.            java.util.logging.Logger.getLogger(ConsultaArticulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  47.        }
  48.        //</editor-fold>
  49.  
  50.  
  51.        java.awt.EventQueue.invokeLater(new Runnable() {
  52.            public void run() {
  53.                new ConsultaArticulos().setVisible(true);
  54.            }
  55.        });
  56.    }
  57.  
  58.    // Variables declaration - do not modify                    
  59.    private javax.swing.JScrollPane jScrollPane1;
  60.    private javax.swing.JList lstArticulos;
  61.    // End of variables declaration                  
  62. }
  63.  
  64.  



Articulo class
Código
  1. public class Articulo {
  2.    private int codigo;
  3.    private String nombre;
  4.    private float precio;
  5.    private int stockActual;
  6.    private int stockMinimo;
  7.    private int categoria;
  8.  
  9.    public Articulo() {
  10.    }
  11.  
  12.    public int getCodigo() {
  13.        return codigo;
  14.    }
  15.  
  16.    public void setCodigo(int codigo) {
  17.        this.codigo = codigo;
  18.    }
  19.  
  20.    public String getNombre() {
  21.        return nombre;
  22.    }
  23.  
  24.    public void setNombre(String nombre) {
  25.        this.nombre = nombre;
  26.    }
  27.  
  28.    public float getPrecio() {
  29.        return precio;
  30.    }
  31.  
  32.    public void setPrecio(float precio) {
  33.        this.precio = precio;
  34.    }
  35.  
  36.    public int getStockActual() {
  37.        return stockActual;
  38.    }
  39.  
  40.    public void setStockActual(int stockActual) {
  41.        this.stockActual = stockActual;
  42.    }
  43.  
  44.    public int getStockMinimo() {
  45.        return stockMinimo;
  46.    }
  47.  
  48.    public void setStockMinimo(int stockMinimo) {
  49.        this.stockMinimo = stockMinimo;
  50.    }
  51.  
  52.    public int getCategoria() {
  53.        return categoria;
  54.    }
  55.  
  56.    public void setCategoria(int categoria) {
  57.        this.categoria = categoria;
  58.    }
  59.  
  60.    @Override
  61.    public String toString() {
  62.        return "Articulo{" + "codigo=" + codigo + ", nombre=" + nombre + ", precio=" + precio + ", stockActual=" + stockActual + ", stockMinimo=" + stockMinimo + ", categoria=" + categoria + '}';
  63.    }
  64.  
  65. }
  66.  
  67.  


« Última modificación: 28 Febrero 2015, 01:29 am por touchi » En línea

3n31ch


Desconectado Desconectado

Mensajes: 445


Grandes conocimientos engendran grandes dudas


Ver Perfil
Re: Ayuda, obtener datos de Objetos en ArrayList
« Respuesta #1 en: 27 Febrero 2015, 21:46 pm »

Podrias poner tu codigo en el foro?

Modifica tu mensaje, copia y pega el codigo, seleccionalo y luego en el combobox que dice GeSHi selecciona JAVA.

De esta manera sera mas facil acceder a el y ayudarte (Nose los demas, pero a mi no me apetece ponerme a descargar nada)


En línea

touchi

Desconectado Desconectado

Mensajes: 8


Ver Perfil
Re: Ayuda, obtener datos de Objetos en ArrayList
« Respuesta #2 en: 27 Febrero 2015, 22:19 pm »

Ahí puse el código, supuse que iba a ser mas organizado ver cada clase separada. Disculpas~
En línea

robertofd1995

Desconectado Desconectado

Mensajes: 172


Ver Perfil
Re: Ayuda, obtener datos de Objetos en ArrayList
« Respuesta #3 en: 27 Febrero 2015, 22:31 pm »

Me parece que tienes una buena liada , a ver para  empezar comentar la clase no seria mala idea , y para seguir que problema tienes al cargar los articulos , le he pegado una vista rapida , pero si lo demas funciona no se que problemas te puede presentar eso .

Y se un poco mas especifico con tu problema , que es lo que no puedes hacer ?

Y porque extiendes 3 JFrame en las 3 clases? Los JPanel y JDialog estan para algo.

Saludos
En línea

3n31ch


Desconectado Desconectado

Mensajes: 445


Grandes conocimientos engendran grandes dudas


Ver Perfil
Re: Ayuda, obtener datos de Objetos en ArrayList
« Respuesta #4 en: 27 Febrero 2015, 22:42 pm »

Lo vi a la rapida, no  lei nada.

Por lo que vi, me huele a código autogenerado de Netbeans. Estoy en lo correcto?

Por otro lado, es mejor que pongas el extracto en donde tienes el problema, no que pongas todooooo el codigo  :rolleyes:
En línea

touchi

Desconectado Desconectado

Mensajes: 8


Ver Perfil
Re: Ayuda, obtener datos de Objetos en ArrayList
« Respuesta #5 en: 27 Febrero 2015, 22:43 pm »

Perdon otra vez por el desorden.

Mi problema es lo que no esta, en realidad lo que necesito saber es como conseguir los valores de los atributos en especifico para responder a lo siguiente.

cantidad de productos de cada tipo.
total de dinero en artículos.
porcentaje de artículos de tipo 2.
Y articulo con el precio mas elevado.

Esta claro que es necesario utilizar un bucle for/ for each, pero no se como obtener esos datos. Si me podes tirar un ejemplo de una nomas de las consignas que puse arriba ya voy a saber por donde agarrar.

sobre lo de los 3 JFrame la verdad es que asi me enseñaron o me están enseñando mejor dicho. Estoy aprendiendo java. Pero la verdad es que no se me da bien programar.
En línea

touchi

Desconectado Desconectado

Mensajes: 8


Ver Perfil
Re: Ayuda, obtener datos de Objetos en ArrayList
« Respuesta #6 en: 27 Febrero 2015, 22:45 pm »

Algunas cosas son auto generadas, digamos los JFrame si son auto generados y lo visual esta echo con el diseñador proporcionado por NetBeans.
En línea

Usuario Invitado


Desconectado Desconectado

Mensajes: 625



Ver Perfil
Re: Ayuda, obtener datos de Objetos en ArrayList
« Respuesta #7 en: 27 Febrero 2015, 22:59 pm »

NOTA: He publicado la respuesta cuando habías puesto el link, por lo que no vi tu actualización hasta ahora.

Coloca el código que no cumple su trabajo aquí. Primero porque así ayudará a personas que tengan el mismo problema y segundo, porque casi nadie se tomará la molestia de crear un proyecto y agregar las clases y demás que ha descargado.

Por lo que dices aquí supongo que estás trabajando con listas para simular una BBDD, ¿cierto?:

Citar
cantidad de productos de cada tipo.
total de dinero en artículos.
porcentaje de artículos de tipo 2.
Y articulo con el precio mas elevado.

Ok, vamos por partes como dijo Jack el destripador ^^. Primer, creamos un Value Object que representa a un producto:

Código
  1. public class ProductVO {
  2.    private Integer id;
  3.    private String name;
  4.    private String description;
  5.    private Double price;
  6.    private Integer category;
  7.  
  8.    public ProductVO() {}
  9.  
  10.    public ProductVO(Integer id, String name, String description, Double price, Integer category) {
  11.        this.id = id;
  12.        this.name = name;
  13.        this.description = description;
  14.        this.price = price;
  15.        this.category = category;
  16.    }
  17.    /*public ProductVO(Object... data) {
  18.        
  19.         for(byte i=0; i<data.length; i++) {
  20.             String curObjectClassName = data[i].getClass().getSimpleName();
  21.             switch(curObjectClassName.toLowerCase()) {
  22.                 case "byte": this.id = (Byte) id;
  23.                 case "string":
  24.                     switch(i) {
  25.                         case 1: this.name = (String) data[i]; break;
  26.                         case 2: this.username = (String) data[i]; break;
  27.                         case 4: this.category = (String) data[i]; break;
  28.                     }; break;
  29.                 case "double": this.price = (Double) price; break;
  30.             }
  31.         }
  32.     }*/
  33.  
  34.    public Integer getId() { return id; }
  35.  
  36.    public void setId(Integer id) { this.id = id; }
  37.  
  38.    public String getName() { return name; }
  39.  
  40.    public void setName(String name) { this.name = name; }
  41.  
  42.    public String getDescription() { return description; }
  43.  
  44.    public void setDescription(String description) { this.description = description; }
  45.  
  46.    public Double getPrice() { return price; }
  47.  
  48.    public void setPrice(Double price) { this.price = price; }
  49.  
  50.    public Integer getCategory() { return category; }
  51.  
  52.    public void setCategory(Integer category) { this.category = category; }
  53.  
  54. }

Luego, creamos el objeto encargado de manejar las consultas e inicializar la lista:

Código
  1. import java.util.Collections;
  2. import java.util.List;
  3. import java.util.ArrayList;
  4.  
  5.  
  6. public class ProductQuery {
  7.    private static List<ProductVO> productsList = new ArrayList<>();
  8.  
  9.    static {
  10.        Collections.addAll(productsList,
  11.            new ProductVO(1, "Cepillo Colgate super", "Cepillo de dientes extra duradero", 18.5d, 1),
  12.            new ProductVO(2, "Jarabe para tos", "Jarabe para la tos sabor miel", 25.90d, 2),
  13.            new ProductVO(3, "Aspirina", "Pastilla para el dolor de cabeza", 4.3d, 2)
  14.        );
  15.    }
  16.  
  17.    public int[] getProductExistencesByCategory(int category) {
  18.        final int SEARCH_ALL = -1;
  19.        final int GROOMING_CATEGORY = 1;
  20.        final int MEDICINE_CATEGORY = 2;
  21.        int groomingCategoryExistences = 0; // cantidad de productos en aseo personal
  22.        int medicineCategoryExistences = 0; // cantidad de productos en medicina
  23.        int requestCategoryExistences = 0;
  24.  
  25.        for(ProductVO product : productsList) {
  26.            if(category != SEARCH_ALL) {
  27.                if(product.getCategory() == category) {
  28.                    requestCategoryExistences++;
  29.                }
  30.            } else {
  31.                if(product.getCategory() == GROOMING_CATEGORY)
  32.                  groomingCategoryExistences++;
  33.                if(product.getCategory() == MEDICINE_CATEGORY)
  34.                  medicineCategoryExistences++;
  35.            }
  36.        }
  37.        if(category != SEARCH_ALL)
  38.            return new int[] { requestCategoryExistences };
  39.        else
  40.            return new int[] {groomingCategoryExistences, medicineCategoryExistences};    
  41.    }
  42.  
  43.    public Double getTotalAmountOfProducts() {
  44.        Double totalAmount = 0d;
  45.  
  46.        for(ProductVO product : productsList) {
  47.            totalAmount += product.getPrice();
  48.        }
  49.        return totalAmount;
  50.    }
  51.  
  52.    public ProductVO getMostValuedProduct() {
  53.        ProductVO mostValued = productsList.get(0);
  54.  
  55.        for(ProductVO product : productsList) {
  56.            if(product.getPrice() > mostValued.getPrice())
  57.                mostValued = product;
  58.        }
  59.  
  60.        return mostValued;
  61.    }
  62.  
  63.  
  64. }

El código entre static {}, se ejecutará cuando el ClassLoader cargue la clase, es decir, se ejecutará de forma simultánea a la compilación. Esto para que la lista de productos esté disponible ni bien ejecutamos la aplicación.

Por último, hacemos pruebas:

Código
  1. public class ProductsTest{
  2.  
  3.     public static void main(String []args){
  4.        ProductQuery query = new ProductQuery();
  5.        int[] categoryExistences = query.getProductExistencesByCategory(-1);
  6.        int[] medicineCategoryExistences = query.getProductExistencesByCategory(2);
  7.        ProductVO mostValuedProduct = query.getMostValuedProduct();
  8.        Double totalAmount = query.getTotalAmountOfProducts();
  9.  
  10.        System.out.println("Products existences by category: ");
  11.        printArray(categoryExistences);
  12.        System.out.println("Products existences by medicine category: ");
  13.        printArray(medicineCategoryExistences);
  14.        System.out.println("Most valued product: "+mostValuedProduct.getName());
  15.        System.out.println("Total amount of products: "+totalAmount);
  16.     }
  17.  
  18.     public static void printArray(int[] array) {
  19.       for(int value : array)
  20.         System.out.println(value);
  21.     }
  22.  
  23. }


Resutados:

Código:
Products existences by category: 
1
2
Products existences by medicine category:
2
Most valued product: Jarabe para tos
Total amount of products: 48.699999999999996


Si tienes alguna duda, no dudes en preguntar.
« Última modificación: 27 Febrero 2015, 23:00 pm por Gus Garsaky » En línea

"La vida es muy peligrosa. No por las personas que hacen el mal, si no por las que se sientan a ver lo que pasa." Albert Einstein
3n31ch


Desconectado Desconectado

Mensajes: 445


Grandes conocimientos engendran grandes dudas


Ver Perfil
Re: Ayuda, obtener datos de Objetos en ArrayList
« Respuesta #8 en: 27 Febrero 2015, 23:05 pm »

Pues nada, estaba escribiéndote el ejemplo pero Gus lo publico antes. Con eso ha de ser suficiente. Suerte ^^

PD: Un dia de estos hare una campaña para exterminar a todos los profesores que enseñen a programar usando el "diseñador" de netbeans.

En línea

Usuario Invitado


Desconectado Desconectado

Mensajes: 625



Ver Perfil
Re: Ayuda, obtener datos de Objetos en ArrayList
« Respuesta #9 en: 27 Febrero 2015, 23:14 pm »

+1 Nacho. Avísame cuándo es la  campaña xD
En línea

"La vida es muy peligrosa. No por las personas que hacen el mal, si no por las que se sientan a ver lo que pasa." Albert Einstein
Páginas: [1] 2 Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
consulta ciclo for 100.000.000 de datos en un arraylist
Java
neomadara 2 1,655 Último mensaje 1 Mayo 2014, 22:04 pm
por ivancea96
ArrayList varios tipos de Objetos
Java
Winterz 0 1,613 Último mensaje 28 Mayo 2014, 17:36 pm
por Winterz
¿Cómo manejar un ArrayList de objetos?
Java
luchi 2 2,850 Último mensaje 3 Septiembre 2016, 18:28 pm
por luchi
Obtener datos de un ArrayList [Editado]
Java
i33naxo 0 2,240 Último mensaje 12 Diciembre 2016, 23:26 pm
por i33naxo
Ayuda agregando objetos a un ArrayList
Java
Casvill 6 2,379 Último mensaje 7 Enero 2019, 21:31 pm
por antopixel
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines