ejemplo s java

23
VECTORES BancoIndustrialapp package curso.umg; public class Banco { private String nombreBanco; private String direccion; private Cliente[] listaCliente; private int cantidad; public Banco () { cantidad = 0; listaCliente = new Cliente[3]; } public void adicionarCliente(Cliente cliente) { listaCliente[cantidad] = cliente; cantidad++; } public String getNombreBanco() { return nombreBanco; } public String getDireccion() { return direccion; } public int getCantidad() { return cantidad; } public void setNombreBanco(String nombreBanco) { this.nombreBanco = nombreBanco; } public void setDireccion(String direccion) { this.direccion = direccion; } public Cliente[] getListaCliente() { return listaCliente; } } package curso.umg; public class Cliente {

Upload: fredy-castillo

Post on 16-Dec-2015

224 views

Category:

Documents


5 download

DESCRIPTION

ejemplo de java

TRANSCRIPT

VECTORES BancoIndustrialapppackage curso.umg;

public class Banco {

private String nombreBanco; private String direccion; private Cliente[] listaCliente; private int cantidad; public Banco () { cantidad = 0; listaCliente = new Cliente[3]; } public void adicionarCliente(Cliente cliente) { listaCliente[cantidad] = cliente; cantidad++; } public String getNombreBanco() { return nombreBanco; } public String getDireccion() { return direccion; } public int getCantidad() { return cantidad; } public void setNombreBanco(String nombreBanco) { this.nombreBanco = nombreBanco; } public void setDireccion(String direccion) { this.direccion = direccion; } public Cliente[] getListaCliente() { return listaCliente; } }

package curso.umg;

public class Cliente { private String nombreCompleto; private int edad; private int salario;

public Cliente() { } public Cliente(String nombreCompleto, int edad, int salario) { this.nombreCompleto = nombreCompleto; this.edad = edad; this.salario = salario; } public String getNombreCompleto() { return nombreCompleto; } public int getEdad() { return edad; } public int getSalario() { return salario; } public void setNombreCompleto(String nombreCompleto) { this.nombreCompleto = nombreCompleto; } public void setEdad(int edad) { this.edad = edad; } public void setSalario(int salario) { this.salario = salario; }}

package curso.umg;

import java.util.HashSet;import java.util.Set;

public class Principal {

/** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Cliente cliente1 = new Cliente("Silvia Olivia", 27, 500); Cliente cliente2 = new Cliente(); cliente2.setNombreCompleto("Fredy Castillo"); cliente2.setEdad(29); cliente2.setSalario(600); Banco banco1 = new Banco(); banco1.setNombreBanco("Industrial"); banco1.setDireccion("Universidad"); banco1.adicionarCliente(cliente1); banco1.adicionarCliente(cliente2); System.out.println("Banco: " + banco1.getNombreBanco() + ", Direccion: " + banco1.getDireccion()); for (int i = 0; i < banco1.getCantidad(); i++) { System.out.println("Cliente: " + banco1.getListaCliente()[i].getNombreCompleto() + ", Edad: " + banco1.getListaCliente()[i].getEdad()); } }}

package curso.umg;

import java.io.BufferedReader;import java.io.InputStreamReader;

public class Principal2 {

public static void main(String[] args) throws Exception{ // TODO code application logic here String valor; double suma = 0; InputStreamReader resultado = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(resultado); System.out.println("Ingrese primer numero: "); valor = br.readLine(); suma = suma + Double.valueOf(valor).doubleValue(); System.out.println("Ingrese segundo numero: "); valor = br.readLine(); suma = suma + Double.valueOf(valor).doubleValue(); System.out.println("Suma Total: " + suma); } }

LISTAS y BD BancoApp

package curso.umg;

import java.util.ArrayList;import java.util.List;

public class Banco { private String nombre; private String direccion; private List listadoClientes;

public Banco(String nombre, String direccion) { this.nombre = nombre; this.direccion = direccion; this.listadoClientes = new ArrayList(); } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public List getListadoClientes() { return listadoClientes; } public void adicionarCliente(Cliente c) { listadoClientes.add(c); } public double salarioTotal() { double salarioTotal = 0; for (Cliente cliente : listadoClientes) { salarioTotal += cliente.getSalario(); } return salarioTotal; }}

package curso.umg;

public class Cliente { private int id; private String nombre; private int edad; private double salario; public Cliente() { } public Cliente(String nombre, int edad, double salario) { this.nombre = nombre; this.edad = edad; this.salario = salario; }

public Cliente(int id, String nombre, int edad, double salario) { this.id = id; this.nombre = nombre; this.edad = edad; this.salario = salario; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public int getEdad() { return edad; } public void setEdad(int edad) { this.edad = edad; } public double getSalario() { return salario; } public void setSalario(double salario) { this.salario = salario; } }

package curso.umg;

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;

public class Principal {

/** * @param args the command line arguments */ public static void main(String[] args) throws IOException, Exception { // TODO code application logic here

int opcion = 0; Banco b = null;

while (opcion != 4) { System.out.println("Bienvenidos a la aplicacion del banco"); System.out.println("Opciones :"); System.out.println("1. Entrar datos del Banco"); System.out.println("2. Adicionar Clientes"); System.out.println("3. Salario total del banco"); System.out.println("4. Salir de la aplicacion"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); opcion = Integer.valueOf(br.readLine()); switch (opcion) { case 1: System.out.println("Nombre del Banco"); String nombre = br.readLine(); System.out.println("Direccion del Banco"); String direccion = br.readLine(); b = new Banco(nombre, direccion); System.out.println("Los datos del banco han sido introducidos"); break; case 2: System.out.println("Nombre del Cliente"); String nombreC = br.readLine(); System.out.println("Edad del Cliente"); int edad = Integer.valueOf(br.readLine()); System.out.println("Salario del cliente"); double salario = Double.valueOf(br.readLine()); b.adicionarCliente(new Cliente(nombreC, edad, salario)); System.out.println("Los datos del cliente han sido introducidos"); break; case 3: System.out.println("El salario total de os clientes del banco es de : " + b.salarioTotal()); case 4: System.out.println("Gracias por utilizar la app del Banco Industrial"); } }

}

}package curso.umg.db;

import curso.umg.Cliente;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.ArrayList;import java.util.List;

public class ClienteDao {

private final String OBTENER_CLIENTES = "SELECT * FROM Cliente"; private final String INSERTAR_Cliente = "INSERT INTO Cliente(nombre,edad,salario) VALUES (?,?,?)"; private final String ELIMINAR_Cliente_POR_ID = "DELETE FROM Cliente WHERE id= ?"; private final String BUSCAR_Cliente_POR_NOMBRE = "SELECT * FROM Cliente WHERE nombre= ?"; public List listadoDeClientes(Connection connection) throws Exception { PreparedStatement ps = connection.prepareStatement(OBTENER_CLIENTES); ResultSet rs = ps.executeQuery(); Cliente c = null; List clientes = new ArrayList(); while (rs.next()) { int id = rs.getInt("Id"); String nombre = rs.getString("Nombre"); int edad = rs.getInt("Edad"); double salario = rs.getDouble("salario"); c = new Cliente(id,nombre, edad, salario); clientes.add(c); } rs.close(); return clientes; } public void adicionarCliente(Cliente c, Connection connection) throws Exception { PreparedStatement ps = connection.prepareStatement(INSERTAR_Cliente); ps.setString(1, c.getNombre()); ps.setInt(2, c.getEdad()); ps.setDouble(3, c.getSalario()); ps.execute(); ps.close(); } public void eliminarCliente(int id, Connection connection) throws Exception { PreparedStatement ps = connection.prepareStatement(ELIMINAR_Cliente_POR_ID); ps.setInt(1, id); ps.execute(); ps.close(); } public Cliente buscarClubPorNombre(String nombreCliente, Connection connection) throws Exception { PreparedStatement ps = connection.prepareStatement(BUSCAR_Cliente_POR_NOMBRE); ps.setString(1, nombreCliente); ResultSet rs = ps.executeQuery(); Cliente c = null; if (rs.next()) { int id = rs.getInt("id"); String nombre = rs.getString("nombre"); int edad = rs.getInt("edad"); double salario = rs.getDouble("salario"); c = new Cliente(nombre, edad, salario); } rs.close(); return c; }}package curso.umg.db;

import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;

public class JDBCUtil {

private static final String url = "jdbc:ucanaccess://C:/Users/alumno/Documents/Registro.accdb"; private static String user = ""; private static String password = ""; private static Connection connection = null; public static Connection getConnection(String url, String user, String password) throws SQLException { connection = DriverManager.getConnection(url, user, password); return connection; } public static Connection getConnection() throws SQLException { return getConnection(url, user, password);

} public static void close() throws SQLException { connection.close(); }}

package curso.umg.visual;

import curso.umg.Banco;import curso.umg.Cliente;import curso.umg.db.ClienteDao;import curso.umg.db.JDBCUtil;import java.awt.event.KeyEvent;import java.sql.Connection;import java.sql.SQLException;import java.util.List;import java.util.logging.Level;import java.util.logging.Logger;import javax.swing.JOptionPane;import javax.swing.table.DefaultTableModel;

/** * * @author ore */public class BancoFrame extends javax.swing.JFrame {

private Banco banco; private DefaultTableModel model; private ClienteDao dao; private Connection conn;

/** * Creates new form BancoFrame */ public BancoFrame() { initComponents(); dao = new ClienteDao(); model = new DefaultTableModel(new Object[]{"Id", "Nombre", "Edad", "Salario"}, 0); jTable1.setModel(model);

banco = new Banco("GyT", "calle 6ta AVE"); try { conn = JDBCUtil.getConnection(); actualizarCampos(); } catch (SQLException ex) { Logger.getLogger(BancoFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(BancoFrame.class.getName()).log(Level.SEVERE, null, ex); }

}

/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // private void initComponents() {

jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jTextField2 = new javax.swing.JTextField(); jTextField3 = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem1 = new javax.swing.JMenuItem();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Sistema de Gestin Bancaria");

jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del Cliente")); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

jLabel1.setText("Nombre:"); jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(16, 30, -1, -1));

jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); jPanel1.add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(61, 27, 101, -1));

jLabel2.setText("Edad:"); jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 60, -1, -1));

jLabel3.setText("Salario:"); jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(21, 94, -1, -1));

jButton1.setText("Adicionar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel1.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(61, 129, -1, -1)); jPanel1.add(jTextField2, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 60, 45, -1)); jPanel1.add(jTextField3, new org.netbeans.lib.awtextra.AbsoluteConstraints(61, 91, 63, -1));

jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] {

}, new String [] { "Nombre", "Edad", "Salario" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.Integer.class, java.lang.Double.class }; boolean[] canEdit = new boolean [] { false, false, false };

public Class getColumnClass(int columnIndex) { return types [columnIndex]; }

public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jTable1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { jTable1KeyReleased(evt); } }); jScrollPane1.setViewportView(jTable1);

jMenu1.setText("File");

jMenuItem2.setText("Salario Total"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu1.add(jMenuItem2);

jMenuItem1.setText("Salir"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem1);

jMenuBar1.add(jMenu1);

setJMenuBar(jMenuBar1);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 352, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addContainerGap(23, Short.MAX_VALUE)) );

pack(); }//

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) { try { conn.close(); System.exit(0); } catch (Exception e) { } // TODO add your handling code here:

}

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

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: //recogida de datos del cliente String nombre = jTextField1.getText(); int edad = Integer.parseInt(jTextField2.getText()); double salario = Double.parseDouble(jTextField3.getText()); try { //banco.adicionarCliente(new Cliente(nombre, edad, salario)); dao.adicionarCliente(new Cliente(nombre, edad, salario), conn); actualizarCampos(); } catch (Exception ex) { Logger.getLogger(BancoFrame.class.getName()).log(Level.SEVERE, null, ex); }

//limpiar Campos jTextField1.setText(""); jTextField2.setText(""); jTextField3.setText(""); }

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

JOptionPane.showMessageDialog(this, "El salario de todos los clientes es de: " + banco.salarioTotal()); }

private void jTable1KeyReleased(java.awt.event.KeyEvent evt) { // TODO add your handling code here: int opcion = -1; if (evt.getKeyCode() == KeyEvent.VK_DELETE && jTable1.getSelectedRowCount() != 0) { opcion = JOptionPane.showConfirmDialog(this, "Seguro desea eliminar un cliente?", "Confirmacion", JOptionPane.YES_NO_OPTION);

if (opcion == JOptionPane.YES_OPTION) { try { int id = Integer.valueOf(jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 0).toString()); dao.eliminarCliente(id, conn); actualizarCampos(); } catch (Exception ex) { Logger.getLogger(BancoFrame.class.getName()).log(Level.SEVERE, null, ex); } } }

}

/** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ // /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(BancoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(BancoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(BancoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(BancoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //

/* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new BancoFrame().setVisible(true); } }); }

// Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JMenu jMenu1; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; // End of variables declaration

public void actualizarCampos() throws Exception { //actualizar el modelo while (model.getRowCount() != 0) { model.removeRow(0); } // model.getDataVector().removeAllElements(); List listado = dao.listadoDeClientes(conn); for (Cliente cliente : listado) { model.addRow(new Object[]{cliente.getId(), cliente.getNombre(), cliente.getEdad(), cliente.getSalario()}); }

}

}LISTAS UNIVERSIDADpackage umg.curso;

import java.util.ArrayList;import java.util.List;

public class Profesor { private String nombre; private String especialidad; private List lEstudiantes = new ArrayList();

public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; }

public String getEspecialidad() { return especialidad; } public void setEspecialidad(String especialidad) { this.especialidad = especialidad; } public List getlEstudiantes() { return lEstudiantes; } public void setlEstudiantes(Estudiante estudiante) { this.lEstudiantes.add(estudiante); }}package umg.curso;

import java.util.ArrayList;import java.util.List;

/** * * @author alumno */public class Estudiante { private String nombre; private int edad; List lAsignaturas = new ArrayList();

public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public int getEdad() { return edad; } public void setEdad(int edad) { this.edad = edad; } public List getlAsignaturas() { return lAsignaturas; } public void setlAsignaturas(Asignatura asignatura) { this.lAsignaturas.add(asignatura); } public float getPromedio() { float promedio = 0; int sumatoriaNotas = 0; int cantidadNotas = 0; for(Asignatura a: this.getlAsignaturas()) { sumatoriaNotas += a.getNota(); cantidadNotas++; } //Calcular el promedio promedio = sumatoriaNotas / cantidadNotas; return promedio; }}

package umg.curso;

public class Asignatura { private String nombre; private int nota; private int cantEvaluaciones;

public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public int getNota() { return nota; } public void setNota(int nota) { this.nota = nota; } public int getCantEvaluaciones() { return cantEvaluaciones; } public void setCantEvaluaciones(int cantEvaluaciones) { this.cantEvaluaciones = cantEvaluaciones; }}

package umg.curso;

import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.List;

public class Universidad {

public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Profesor p = new Profesor(); p.setNombre("Orestes Febles"); p.setEspecialidad("Programacin e Investigacin"); //INICIALIZAR LAS ASIGNATURAS Asignatura a1 = new Asignatura(); a1.setNombre("Programacin Avanzada en Java"); a1.setNota(100); a1.setCantEvaluaciones(1);

Asignatura a2 = new Asignatura(); a2.setNombre("Programacin en Android"); a2.setNota(90); a2.setCantEvaluaciones(1); Asignatura a3 = new Asignatura(); a3.setNombre("Programacin en Perl"); a3.setNota(95); a3.setCantEvaluaciones(1); Asignatura a4 = new Asignatura(); a4.setNombre("Programacin en Ruby"); a4.setNota(71); a4.setCantEvaluaciones(1); Asignatura a5 = new Asignatura(); a5.setNombre("Programacin en Phyton"); a5.setNota(95); a5.setCantEvaluaciones(1); Estudiante e1 = new Estudiante(); e1.setNombre("Daniel Garca"); e1.setEdad(25); Estudiante e2 = new Estudiante(); e2.setNombre("Miguel Lopez"); e2.setEdad(26); //SETEAR LAS ASIGNATURAS AL ESTUDIANTE e1.setlAsignaturas(a1); e1.setlAsignaturas(a3); e2.setlAsignaturas(a2); e2.setlAsignaturas(a4); //SETEAR LOS ESTUDIANTES AL PROFESOR p.setlEstudiantes(e1); p.setlEstudiantes(e2); ObtenerMejorPromedio(p.getlEstudiantes()); } public static Estudiante ObtenerMejorPromedio(List l) { int sumatoriaNotas = 0; int cantidadNotas = 0; float promedio = 0; float mejorPromedio = 0; int iActualEstudiante = -1; int iEstudianteMejorPromedio = 0; for(Estudiante e: l) { sumatoriaNotas = 0; cantidadNotas = 0; iActualEstudiante++; promedio = e.getPromedio(); if (promedio > mejorPromedio) { mejorPromedio = promedio; iEstudianteMejorPromedio = iActualEstudiante; } } System.out.println("Estudiante con mejor promedio es " + l.get(iEstudianteMejorPromedio).getNombre() + " con promedio de " + String.valueOf(mejorPromedio)); return l.get(iEstudianteMejorPromedio); } }