Reporte Del Ejercicio 8
July 7, 2022 | Author: Anonymous | Category: N/A
Short Description
Download Reporte Del Ejercicio 8...
Description
TECNOLÓGICO NACIONAL DE MÉXICO INSTITUTO TECNOLÓGICO DE TAPACHULA “LIBERTAD DE ESPÍRITU EN CIENCIA Y TECNOLOGÍA” TECNOLOGÍA”
ASIGNATURA: PROGRAMACIÓN ORIENTADA A OBJETOS. TEMA 5: 5: “EXCEPCIONES “EXCEPCIONES”” TITULO DEL ENSAYO: REPORTE DEL EJERCICIO 8. PRESENTA: MORALES SOLÍS BRANDON OMAR. NO. CONTROL: 20510397. 20510397. SEMESTRE: 2. GRUPO: B. CATEDRÁTICO: LIC. GUSTAVO REYES HERNANDEZ. FECHA: 29/06/2021.
Objetivo.
Reutilizar una aplicación vieja que en este caso será el ejercicio 2 y con base a lo ya realizado darle un tratamiento con ayuda de un manejador de excepciones para así lograr que el programa no se cierre de una manera inesperada o imprima en la terminal mensajes de error.
Desarrollo. Como se mencionó anteriormente se reutilizará la información del ejerció 2.
Código d el prog rama rama..
Código de la clase P Persona: ersona: /* * To change this license header, head er, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package backEnd; import javax.swing.JO javax.swing.JOptionPane; ptionPane; /** * * @author Brandon Omar Morales Solís */ public class Person { //Atributos private String name; private byte age;
private char sex; private String rfc; private String nip; //Constructor para inicializar las variables public Person() { name = ""; age = 0; sex = ' '; rfc = ""; nip = ""; }
//Método constructor public Person(String name, byte age, char sex, String rfc, String nip) { this.name = name; this.age = age; this.sex = sex; this.rfc = rfc; this.nip = nip; } /** * Método que retorna una cadena con los datos de la persona * * @return los datos de la persona p ersona */ public String showDates() { String chain; chain = "Nombre: " + name + " Edad: " + age + " Sexo: " + sex + " RFC: " + rfc; JOptionPane.showMessageDialog(null, chain);
return chain; } /** * Método que determina si la persona es mayor de edad * * @return True si es mayor de edad y false si es menor de edad */ public boolean Older() { if (age >= 18) { return true; } else { return false; } } /** * @return El nombre de la persona */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; }
/**
* @return la edad */ public byte getAge() { return age; } /** * @param age the age to set */ public void setAge(byte age) { this.age = age; }
/** * @return sexo */ public char getSex() { return sex; } /** * @param sex the sex to set */ public void setSex(char sex) { this.sex = sex; } /** * @return RFC */ public String getRfc() {
return rfc; } /** * @param rfc the rfc to set */ public void setRfc(String rfc) { this.rfc = rfc; } public String getNip() { return nip; } public void setNip(String nip) { this.nip = nip; }
}
Código de la clase cuenta bancaria. /* * To change this license header, head er, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package backEnd;
import javax.swing.JO javax.swing.JOptionPane; ptionPane;
/** * * @author Brandon Omar Morales Solís */ public class bankAccount {
//Atributos private Person headline; private float balance; private String accountNumber; private String nip;
//Método constructor para inicializar los valores public bankAccount() { headline = new Person(); balance = 0; accountNumber = ""; nip = "";
}
//Constructor public bankAccount(Person headline, float balance, String accountNumber, String nip) { this.headline = headline; this.balance = balance; this.accountNumber = accountNumber; this.nip = nip; }
/** * Retira una cantidad del saldo de la cuenta bancaria * * @param amount importe que sera retirado de la cuenta */ public void remove(float amount) { balance -= amount; }
/** * Este método incrementa el saldo de la cuenta de la cantidad especificada * si la cantidad es negativa no realiza nada. * * @param amount es el importe a depositar en la cuenta bancaria */ public void toDeposit(float amount) { if (amount >= 0) { balance += amount;
}
}
public void viewBalance() { JOptionPane.showMessageDialog(null, "Número de cuenta: " + accountNumber + " Titular: " + headline.getName() + " Saldo de la cuenta: " + balance); }
@Override public boolean equals(Object p) { return (this.accountNumber.equals(( (this.accountNumber.equals(((bankAccount) (bankAccount) p p).accountNumber)) ).accountNumber));; }
/** * @return the headline */ public Person getHeadline() { return headline; } /** * @param headline the headline to set */ public void setHeadline(Person headline) { this.headline = headline; }
/** * @return the balance */ public float getBalance() { return balance; }
/** * @param balance the balance to set */ public void setBalance(float balance) { this.balance = balance; }
/** * @return the accountNumber */ public String getAccountNumber() { return accountNumber; }
/** * @param accountNumber the accountNumber to set */ public void setAccountNumber(String accountNumber) { this.accountNumber = accountNumber; }
public String getNip() { return nip; }
public void setNip(String nip) { this.nip = nip; }
}
Código d e la int erfaz gráfi gráfica. ca.
/* * To change this license header, head er, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package FronEnd ;
import backEnd.Person ; import backEnd.bankAccount ; import java.util.Arrays ; import javax.swing.JOptionPane ;
/** * * @author brand
*/ public class Atm extends javax.swing.JFrame {
bankAccount[] card; //Arreglo de cuentas bancarias Person client; /** * Creates new form Atm */ public Atm() { initComponents(); card = new bankAccount[3]; //Se crea el arreglo de 3 elementos client = new Person("Brandon Omar Morales Solís", (byte) 18, 'M', "123456788768", "3178"); card[0] = new bankAccount(client, 4500, "3300", "3178"); client = new Person("Angel Ignacio Escobar Osorio", (byte) 19, 'M', "5579109001058094", "3289"); card[1] = new bankAccount(client, 10000, "5200", "3289"); client = new Person("Jazmin Mijangos López", (byte) 18, 'F', "1234567890123456", "4391"); card[2] = new bankAccount(client, 9999, "2038", "4391"); }
/** * Este método busca en el arreglo un número de cuenta específico e specífico * * @param t corresponde al arreglo de cuentas bancarias * @param b cuenta bancaria * @return indice del arreglo que corresponde a la cuenta buscar. Si no
* se encuentra la cuenta en el arreglo regresa -1 */ private int accountSearch(bankAccount[] t, bankAccount b) { if (Arrays.asLis (Arrays.asList(t).contains(b)) t(t).contains(b)) { return Arrays.asList(t Arrays.asList(t).indexOf(b); ).indexOf(b); } else { return -1; } }
/** * 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() {
btnRemove = new javax.swing.JButton() javax.swing.JButton();; btnDeposit = new javax.swing.JButton( javax.swing.JButton(); ); btnBalance = new javax.swing.JButton() javax.swing.JButton();; btnSearch = new javax.swing.JButton( javax.swing.JButton(); ); jLabel1 = new javax.swing.JLabel(); javax.swing.JLabel(); txtAcountNumber = new javax.swing.JTextFi javax.swing.JTextField(); eld(); lblTitular = new javax.swing.JLabel(); lblBalance = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); javax.swing.JLabel();
lblNewBalance = new javax.swing.JLabel() javax.swing.JLabel();; txtAmount = new javax.swing.JTextField( javax.swing.JTextField(); );
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Cajero ATM");
btnRemove.setFont(new java.awt.Font("Arial", java.awt.Font("Arial", 1, 18)); // NOI18N btnRemove.setMnemonic('R'); btnRemove.setText("Retirar"); btnRemove.setToolTipText("Retira btnRemove.setToolTipText("Ret ira dinero de tu cuenta"); btnRemove.addActionListener(new java.awt.event.ActionListener() java.awt.event.ActionListener() { public void actionPerformed(java.aw actionPerformed(java.awt.event.ActionEvent t.event.ActionEvent evt) { btnRemoveActionPerformed(evt); } });
btnDeposit.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N btnDeposit.setMnemonic('D'); btnDeposit.setText("Depositar"); btnDeposit.setToolTipText("Deposita btnDeposit.setToolTipText("De posita dienro en tu cuenta"); btnDeposit.addActionListener(new btnDeposit.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed(java.aw actionPerformed(java.awt.event.ActionEvent t.event.ActionEvent evt) { btnDepositActionPerformed(evt); } });
btnBalance.setFont(new java.awt.Font("Arial", java.awt.Font("Arial", 1, 18)); // NOI18N btnBalance.setMnemonic('D');
btnBalance.setText("Datos"); btnBalance.setToolTipText("Consulta btnBalance.setToolTipText("Cons ulta saldo"); btnBalance.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.aw actionPerformed(java.awt.event.ActionEvent t.event.ActionEvent evt) { btnBalanceActionPerformed(evt); } });
btnSearch.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N btnSearch.setMnemonic('B'); btnSearch.setText("Buscar btnSearch.setText("Busc ar "); btnSearch.setToolTipText("Busca btnSearch.setToolTipText("Busc a el núme número ro de cuenta"); btnSearch.addActionListener(new java.awt.event.ActionListener() java.awt.event.ActionListener() { public void actionPerformed(java.aw actionPerformed(java.awt.event.ActionEvent t.event.ActionEvent evt) { btnSearchActionPerformed(evt); } });
jLabel1.setFont(new java.awt.Font("Arial", java.awt.Font("Arial", 1, 18)); //// NOI18N jLabel1.setText("Número de cuenta"); cuenta");
txtAcountNumber.setFont(new txtAcountNumber.setFont( new java.awt.Font("Arial", 0, 18)); // NOI18N txtAcountNumber.setToolTipText("Digite txtAcountNumber.setToolTi pText("Digite su número de cuenta bancaria"); txtAcountNumber.addActionListener(new txtAcountNumber.addActionLis tener(new java.awt.event.ActionListener() { public void actionPerformed(java.aw actionPerformed(java.awt.event.ActionEvent t.event.ActionEvent evt) { txtAcountNumberActionPerformed(evt); } });
lblTitular.setFont(new java.awt.Font("Arial", java.awt.Font("Arial", 1, 18)); // NOI18N lblTitular.setText("Titular:");
lblBalance.setFont(new java.awt.Font("Arial", java.awt.Font("Arial", 1, 18)); // NOI18N lblBalance.setText("Saldo:");
jLabel2.setFont(new java.awt.Font("Arial", java.awt.Font("Arial", 1, 18)); //// NOI18N jLabel2.setText("Cantidad:");; jLabel2.setText("Cantidad:")
lblNewBalance.setFont(new java.awt.Font("Arial", java.awt.Font("Arial", 1, 18)); // NOI18N lblNewBalance.setText("Nuevo saldo: ");
txtAmount.setFont(new java.awt.Font("Arial", java.awt.Font("Arial", 1, 18)); // NOI18N txtAmount.setHorizontalAlignment(javax.swing.JTextField.RIGHT); txtAmount.setText("0");
javax.swing.GroupLayout layout layout = new javax.swing.GroupLayout(getContentPane()); javax.swing.GroupLayout(getCont entPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG) .addGroup(layout.createSequentialGroup() .addComponent(lblBalance)
.addGap(217, 217, 217)) .addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG) .addComponent(txtAcountNumber) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG) .addComponent(lblTitular) .addComponent(lblNewBalance) .addComponent(btnSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.PR EFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE) javax.swing.GroupLayout.PR EFERRED_SIZE) .addComponent(jLabel1) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAU LT_SIZE, Short.MAX_VALUE) .addComponent(txtAmount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.PR EFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))) javax.swing.GroupLayout.PR EFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG, false) .addComponent(btnRemove, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.Alig nment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAU LT_SIZE, 117, Short.MAX_VALUE)
.addComponent(btnBalance, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.Alig nment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAU LT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAU LT_SIZE, Short.MAX_VALUE)) .addComponent(btnDeposit, javax.swing.GroupLayout.Alignment.TRAILING)) javax.swing.GroupLayout.Alig nment.TRAILING)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jLabel1) .addGap(10, 10, 10) .addComponent(txtAcountNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.PR EFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAU LT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) javax.swing.GroupLayout.PR EFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(btnRemove, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.PR EFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))) javax.swing.GroupLayout.PR EFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnSearch) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.R ELATED, 43, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILI NG) .addGroup(layout.createSequentialGroup() .addComponent(lblTitular) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.R ELATED, 27, Short.MAX_VALUE) .addComponent(lblBalance)) .addComponent(btnDeposit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.PR EFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)) javax.swing.GroupLayout.PR EFERRED_SIZE)) .addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG, false) .addGroup(layout.createSequentialGroup() .addGap(9, 9, 9) .addComponent(btnBalance, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.PR EFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)) javax.swing.GroupLayout.PR EFERRED_SIZE)) .addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASEL INE) .addComponent(jLabel2) .addComponent(txtAmount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.PR EFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAU LT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) javax.swing.GroupLayout.PR EFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAU LT_SIZE, Short.MAX_VALUE) .addComponent(lblNewBalance)))
.addContainerGap(28, Short.MAX_VALUE)) );
pack(); setLocationRelativeTo(null); }//
private void btnSearchActionPerformed(java.awt.event.Acti btnSearchActionPerformed(java.awt.event.ActionEvent onEvent evt) { // TODO add your handling code here: bankAccount bill; int index; bill = new bankAccount();
bill.setAccountNumber(txtAcountNumber.getText()); index = accountSearch(card, bill);
if (index > -1) { lblTitular.setText("Titular: lblTitular.setText( "Titular: " + card[index].getHeadline().getName()); lblBalance.setText("Saldo: lblBalance.setText(" Saldo: " + card[index].getBalance()); } else { JOptionPane.showMessageDialog(this, "El número de cuenta digitado JOptionPane.showMessageDialog(this, no existe"); } }
private void btnDepositActionPerformed(java.awt.event.ActionEvent btnDepositActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: bankAccount bill; int index;
bill = new bankAccount();
bill.setAccountNumber(txtAcountNumber.getText()); index = accountSearch(card, bill);
if (index > -1) { card[index].toDeposit(Float.parseFloat(txtAmount.getText())); lblNewBalance.setText("Nuevo lblNewBalance.setText( "Nuevo saldo: " + card[index].getBalance());
} else { JOptionPane.showMessageDialog(this, "El número d JOptionPane.showMessageDialog(this, de e cuenta digitado no existe"); } }
private void btnRemoveActionPerformed(java.awt.event.ActionEvent btnRemoveActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: bankAccount bill; int index; bill = new bankAccount();
bill.setAccountNumber(txtAcountNumber.getText()); index = accountSearch(card, bill);
if (index > -1) { card[index].remove(Float.parseFloat(txtAmount.getText())); lblNewBalance.setText("Nuevo lblNewBalance.setText( "Nuevo saldo: " + card[index].getBalance());
} else {
JOptionPane.showMessageDialog(t JOptionPane.showMessageDialog(this, his, "El número de cuenta digitado no existe"); }
}
private void btnBalanceActionPerformed(java.awt.event.ActionEvent btnBalanceActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: bankAccount bill; int index; bill = new bankAccount();
bill.setAccountNumber(txtAcountNumber.getText()); index = accountSearch(card, bill);
if (index > -1) { card[index].viewBalance(); } else { JOptionPane.showMessageDialog(this, "El número d JOptionPane.showMessageDialog(this, de e cuenta digitado no existe"); } }
private void txtAcountNumberActionPerf txtAcountNumberActionPerformed(java.awt.event.Acti ormed(java.awt.event.ActionEvent onEvent evt) { // TODO add your handling code here: }
/** * @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 n ot available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswi http://download.oracle.com/jav ase/tutorial/uiswing/lookandfeel/plaf.html ng/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) javax.swing.UIManager.getIns talledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); javax.swing.UIManager.se tLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Atm.class.getName()).log(java.util.logging.Level java.util.logging.Logger.getLogger(Atm.class.getName()).log(java .util.logging.Level .SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Atm.class.getName()).log(java.util.logging.Level java.util.logging.Logger.getLogger(Atm.class.getName()).l og(java.util.logging.Level .SEVERE, null, ex); } catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Atm. java.util.logging.Logger.getLogger(Atm.class.getName()).l class.getName()).log(java.util.logging.Level og(java.util.logging.Level .SEVERE, null, ex);
} catch (javax.swing.Unsupport (javax.swing.UnsupportedLookAndFeelException edLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Atm.class.getName()).log(java.util.logging.Level java.util.logging.Logger.getLogger(Atm.class.getName()).log(j ava.util.logging.Level .SEVERE, null, ex); } //
/* Create and display the form */ java.awt.EventQueue.invokeLater(new java.awt.EventQueue.invokeLater( new Runnable() { public void run() { new Atm().setVisi Atm().setVisible(true); ble(true); } }); }
// Variables declaration - do not modify mod ify private javax.swing.JButton btnBalance; private javax.swing.JButton btnDeposit; private javax.swing.JButton btnRemove; private javax.swing.JButton btnSearch; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel lblBalance; private javax.swing.JLabel lblNewBalance; private javax.swing.JLabel lblTitular; private javax.swing.JTextField txtAcountNumber; private javax.swing.JTextField txtAmount; // End of variables declaration
}
Resultados sin manejador de excepciones.
Excepción generada porque el usuario digita otro formato de número. Debido a que este programa está diseñando para que el usuario digite tipos de datos da tos float. Está excepción recibe el nombre de RuntimeException(excepciones no comprobadas) en palabras sencillas son errores cometidas por el programador.
Por lo que se prosigue a solucionarlo con un manejador de excepciones e xcepciones es decir se agregara el siguiente fragmento de código: try{ //Atrapa el error. } catch () { //Instrucciones a realizar para tratar el error. } En la parte del código de la interfaz que lo requiera. Esto quedaría de la siguiente manera: /* * To change this license header, head er, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package FronEnd; import backEnd.Person; import backEnd.bankAccount; import java.util.Arrays java.util.Arrays;; import javax.swing.JO javax.swing.JOptionPane; ptionPane; /** * * @author brand */ public class Atm extends javax.swing.JFrame { bankAccount[] card; //Arreglo de cuentas bancarias Person client; /** * Creates new form Atm */ public Atm() { initComponents(); card = new bankAccount[3]; //Se crea el arreglo de 3 elementos client = new Person("Brandon Omar Morales Solís", (byte) 18, 'M', "123456788768", card[0] = new"3178"); bankAccount(client, 4500, "3300", "3178");
client = new Person("Angel Ignacio Escobar Osorio", (byte) 19, 'M', "5579109001058094", "3289"); card[1] = new bankAccount(client, 10000, "5200", "3289"); client = new Person("Jazmin Mijangos López", (byte) 18, 'F', "1234567890123456", "4391"); card[2] = new bankAccount(client, 9999, "2038", "4391"); } /** * Este método busca en el arreglo un número de cuenta específico * * @param t corresponde al arreglo de cuentas bancarias * @param b cuenta bancaria * @return indice del arreglo que corresponde a la cuenta buscar. Si no se * encuentra la cuenta en el arreglo regresa -1 */ private int accountSearch(bankAccount[] t, bankAccount b) { if (Arrays.asList(t).contains(b)) (Arrays.asList(t).contains(b)) { return Arrays.asList(t Arrays.asList(t).indexOf(b); ).indexOf(b); } else { return -1; } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of o f this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // private void initComponents() { btnRemove = new javax.swing.JButton( javax.swing.JButton(); ); btnDeposit = new javax.swing.JButton(); btnBalance = new javax.swing.JButton(); btnSearch = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); javax.swing.JLabel(); txtAcountNumber = new javax.swing.JText javax.swing.JTextField(); Field(); lblTitular = new javax.swing.JLabel(); lblBalance = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); javax.swing.JLabel(); lblNewBalance = new javax.swing.JLabel() javax.swing.JLabel();;
txtAmount = new javax.swing.JT javax.swing.JTextField(); extField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Cajero ATM"); btnRemove.setFont(new java.awt.Font("Arial", java.awt.Font("Arial", 1, 18 18)); )); // NOI18N btnRemove.setMnemonic('R'); btnRemove.setText("Retirar"); btnRemove.setToolTipText("Retira btnRemove.setToolTipText("Retir a dinero de tu cuenta"); btnRemove.addActionListener(new java.awt.event.ActionListener() java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoveActionPerformed(evt); } }); btnDeposit.setFont(new java.awt.Font("Arial", java.awt.Font("Arial", 1, 18)); // NOI18N btnDeposit.setMnemonic('D'); btnDeposit.setText("Depositar"); btnDeposit.setToolTipText("Deposita dienro en tu cuenta"); btnDeposit.setToolTipText("Deposita btnDeposit.addActionListener(new java.awt.event.ActionListener() java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDepositActionPerformed(evt); } }); btnBalance.setFont(new java.awt.Font("Arial", java.awt.Font("Arial", 1, 18 18)); )); // NOI18N btnBalance.setMnemonic('D'); btnBalance.setText("Datos"); btnBalance.setToolTipText("Consulta btnBalance.setToolTipText("Cons ulta saldo"); btnBalance.addActionListener(new java.awt.event.ActionListener() java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnBalanceActionPerformed(evt); } }); btnSearch.setFont(new java.awt.Font("Arial", java.awt.Font("Arial", 1, 14)); // NOI18N btnSearch.setMnemonic('B'); btnSearch.setText("Buscar btnSearch.setText(" Buscar "); btnSearch.setToolTipText("Busca btnSearch.setToolTipText("Bus ca el número de cuenta"); btnSearch.addActionListener(new btnSearch.addActionListener( new java.awt.event.Actio java.awt.event.ActionListener() nListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSearchActionPerformed(evt); }
}); jLabel1.setFont(new java.awt.Font("Arial", java.awt.Font("Arial", 1, 18)); // NOI18N jLabel1.setText("Número de cuenta"); txtAcountNumber.setFont(new txtAcountNumber.setFont( new java.awt.Font("Arial", 0, 18)); // NOI18N txtAcountNumber.setToolTipText("Digite txtAcountNumber.setToolTipText( "Digite su número d de e cuenta bancaria"); txtAcountNumber.addActionListener(new java.awt.event.ActionListener() { txtAcountNumber.addActionListener(new public void actionPerformed(java.awt.event.ActionEvent evt) { txtAcountNumberActionPerformed(evt); } }); lblTitular.setFont(new java.awt.Font("Arial", java.awt.Font("Arial", 1, 18)); // NOI18N lblTitular.setText("Titular:"); lblBalance.setFont(new java.awt.Font("Arial", java.awt.Font("Arial", 1, 18)); // NOI18N lblBalance.setText("Saldo:"); jLabel2.setFont(new java.awt.Font("Arial", java.awt.Font("Arial", 1, 18)); // NOI18N jLabel2.setText("Cantidad:");; jLabel2.setText("Cantidad:") lblNewBalance.setFont(new java.awt.Font("Arial", java.awt.Font("Arial", 1, 18)); // NOI18N lblNewBalance.setText("Nuevo lblNewBalance.setText("Nuev o saldo: "); txtAmount.setFont(new java.awt.Font("Arial", java.awt.Font("Arial", 1, 18)); // NOI18N txtAmount.setHorizontalAlignment(javax.swing.JTextField.RIGHT); txtAmount.setText("0");
javax.swing.GroupLayout layout layout = new javax.swing.GroupLayout(getContentPane()); javax.swing.GroupLayout(getCont entPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG) .addGroup(layout.createSequentialGroup() .addComponent(lblBalance) .addGap(217, 217, 217)) .addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG) .addComponent(txtAcountNumber) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG) .addComponent(lblTitular) .addComponent(lblNewBalance) .addComponent(btnSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.PR EFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE) javax.swing.GroupLayout.PR EFERRED_SIZE) .addComponent(jLabel1) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAU LT_SIZE, Short.MAX_VALUE) .addComponent(txtAmount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.PREFERRED _SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))) javax.swing.GroupLayout.PR EFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG, false) .addComponent(btnRemove, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.Alig nment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAU LT_SIZE, 117, Short.MAX_VALUE) .addComponent(btnBalance, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.Alig nment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAU LT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAU LT_SIZE, Short.MAX_VALUE)) .addComponent(btnDeposit, javax.swing.GroupLayout.Alignment.TRAILING)) javax.swing.GroupLayout.Alig nment.TRAILING)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jLabel1) .addGap(10, 10, 10) .addComponent(txtAcountNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.PR EFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAU LT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) javax.swing.GroupLayout.PR EFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(btnRemove, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.PREFERRED _SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))) javax.swing.GroupLayout.PR EFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnSearch) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 43, .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILI NG) .addGroup(layout.createSequentialGroup() .addComponent(lblTitular) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.R ELATED, 27, Short.MAX_VALUE) .addComponent(lblBalance)) .addComponent(btnDeposit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.PR EFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)) javax.swing.GroupLayout.PR EFERRED_SIZE)) .addGap(20, 20, 20) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG, false) .addGroup(layout.createSequentialGroup() .addGap(9, 9, 9) .addComponent(btnBalance, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.PR EFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)) javax.swing.GroupLayout.PR EFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASEL INE) .addComponent(jLabel2) .addComponent(txtAmount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAU LT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) javax.swing.GroupLayout.PR EFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAU LT_SIZE, Short.MAX_VALUE) .addComponent(lblNewBalance))) .addContainerGap(28, Short.MAX_VALUE)) ); pack(); setLocationRelativeTo(null); }// private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: bankAccount bill; int index; bill = new bankAccount(); bill.setAccountNumber(txtAcountNumber.getText()); index = accountSearch(card, bill); if (index > -1) { lblTitular.setText("Titular: lblTitular.setText( "Titular: " + card[index].getHeadline().getName()); lblBalance.setText("Saldo: lblBalance.setText("Sal do: " + card[index].getBalance()); } else { JOptionPane.showMessageDialog(this, JOptionPane.showMessageDialog(t his, "El número de cuenta digitado no existe"); } } private void btnDepositActionPerformed(j btnDepositActionPerformed(java.awt.event.ActionEvent ava.awt.event.ActionEvent evt) { // TODO add your handling code here: bankAccount bill; int index; bill = new bankAccount();
bill.setAccountNumber(txtAcountNumber.getText()); index = accountSearch(card, bill); if (index > -1) { try { //Código que puede provocar errores card[index].toDeposit(Float.parseFloat(txtAmount.getText())); lblNewBalance.setText("Nuevo lblNewBalance.setText( "Nuevo saldo: " + card[index].getBalance()); } catch (NumberFormatException (NumberFormatException ex) { //Gestión del error NumberFormatException ex JOptionPane.showMessageDialog(null, JOptionPane.showMessageDialog( null, "Error no p puede uede depositar esa cantidad -->" + ex.getMessage()); } } else { JOptionPane.showMessageDialog(this, JOptionPane.showMessageDialog(t his, "El número de cuenta digitado no existe"); } } private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: bankAccount bill; int index; bill = new bankAccount(); bill.setAccountNumber(txtAcountNumber.getText()); index = accountSearch(card, bill); if (index > -1) { try { //Código que puede provocar errores card[index].remove(Float.parseFloat(txtAmount.getText())); lblNewBalance.setText("Nuevo saldo: " + card[index].getBalance()); } catch (NumberFormatException ex) { //Gestión del error NumberFormatException ex JOptionPane.showMessageDialog(null, JOptionPane.showMessageDialog(nu ll, "Error no p puede uede retirar esa cantidad -->" + ex.getMessage()); } } else { JOptionPane.showMessageDialog(this, JOptionPane.showMessageDialog(t his, "El número de cuenta digitado no existe"); }
} private void btnBalanceActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: bankAccount bill; int index; bill = new bankAccount(); bill.setAccountNumber(txtAcountNumber.getText()); index = accountSearch(card, bill); if (index > -1) { card[index].viewBalance(); } else { JOptionPane.showMessageDialog(this, JOptionPane.showMessageDialog(t his, "El número de cuenta digitado no existe"); } } private void txtAcountNumberActionPerf txtAcountNumberActionPerformed(java.awt.event.Ac ormed(java.awt.event.ActionEvent tionEvent evt) { // TODO add your handling code here: } /** * @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()) javax.swing.UIManager.getIns talledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName() javax.swing.UIManager.se tLookAndFeel(info.getClassName()); ); break; }
} } catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Atm.class.getName()).log(java.util.logging.Level java.util.logging.Logger.getLogger(Atm.class.getName()).l og(java.util.logging.Level .SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Atm.class.getName()).log(java.util.logging.Level java.util.logging.Logger.getLogger(Atm.class.getName()).l og(java.util.logging.Level .SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Atm.class.getName()).log(java.util.logging.Level java.util.logging.Logger.getLogger(Atm.class.getName()).l og(java.util.logging.Level .SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Atm.class.getName()).log(java.util.logging.Level java.util.logging.Logger.getLogger(Atm.class.getName()).l og(java.util.logging.Level .SEVERE, null, ex); } // /* Create and display the form */ java.awt.EventQueue.invokeLater(new java.awt.EventQueue.invoke Later(new Runnable() { public void run() { new Atm().setVisible( Atm().setVisible(true); true); } }); } // Variables declaration - do not modify private javax.swing.JButton btnBalance; private javax.swing.JButton btnDeposit; private javax.swing.JButton btnRemove; private javax.swing.JButton btnSearch; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel lblBalance; private javax.swing.JLabel lblNewBalance; private javax.swing.JLabel lblTitular; private javax.swing.JTextField txtAcountNumber; private javax.swing.JTextField txtAmount; // End of variables declaration }
Resultados con manejador de excepciones.
Como podemos ver ya no se generan errores. Se soluciona el error generando un mensaje en una ventana emergente.
Conclusión. Al haber hecho esta práctica de programación puedo decir que las excepciones son casos de error que pueden suceder en un programa provocando que lance mensajes de error en la terminal o se termine cerrando de una manera muy brusca. Por lo que la forma más fácil de resolver este problema que se enfrenta cualquier programador es con tratamiento de yexcepciones que solución. consiste en un fragmento de código que ayuda permiteuncapturar el error dar una posible Otra cosa muy importante que aprendí es que existen dos tipos de excepciones las cuales son: IOException (excepciones comprobadas). En palabras sencillas son errores que no son culpa del desarrollador de Java. RuntimeException (exc (excepciones epciones no compr comprobadas). obadas). En palabras sencillas son errores que son culpa del desarrollador de Java.
•
•
En está practica que realice puedo decir que la excepción cometida es un RuntimeException porque es culpa mía debido a que no programe para el caso en el que el usuario se le ocurriera digitar un tipo de dato que no sea float. Por lo que lo soluciones dándole un tratamiento de excepciones, pero soy consiente que esa no es la mejor manera de solucionarlo debido a que es un error mío por lo que mi obligación es resolver el error sin ayuda del manejo de excepciones debido a que eso no se considera una buena práctica de programación.
Bibliografías. Reyes, G (2021). Manejo de excepciones e xcepciones básicas de Java. YouTube. Recuperado https://www.youtube.com/watch?v=_ozU4ixNHo4 de: https://www.youtube.com/watch?v=_ozU4ixNHo4 de: Reyes, G (2021). Ejemplo de una excepción. Tecnm.mx. Recuperado de: https://tapachula.tecnm.mx/servicios/virtualroom/pluginfile.php/74243/ https://tapachula.tecnm.mx/servicios/v irtualroom/pluginfile.php/74243/mod_resourc mod_resourc e/content/1/EjemploExcepciones.java e/content/1/EjemploExcepciones.java
View more...
Comments