Está en la página 1de 38

TECNOLÓGICO NACIONAL DE MÉXICO

INSTITUTO TECNOLÓGICO DE TAPACHULA


“LIBERTAD DE ESPÍRITU EN CIENCIA Y TECNOLOGÍA”

ASIGNATURA: PROGRAMACIÓN ORIENTADA A


OBJETOS.

TEMA 5: “EXCEPCIONES”

TITULO DEL ENSAYO: REPORTE DEL EJERCICIO 8.

PRESENTA: MORALES SOLÍS BRANDON OMAR.

NO. CONTROL: 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 del programa.

Código de la clase Persona:


/*
* To change this license header, 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.JOptionPane;

/**
*
* @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
*/
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, 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.JOptionPane;

/**
*
* @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(((bankAccount) p).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 de la interfaz gráfica.

/*
* To change this license header, 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
*
* @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)) {
return Arrays.asList(t).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")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

btnRemove = new javax.swing.JButton();


btnDeposit = new javax.swing.JButton();
btnBalance = new javax.swing.JButton();
btnSearch = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
txtAcountNumber = new javax.swing.JTextField();
lblTitular = new javax.swing.JLabel();
lblBalance = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
lblNewBalance = new javax.swing.JLabel();
txtAmount = new javax.swing.JTextField();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Cajero ATM");

btnRemove.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N


btnRemove.setMnemonic('R');
btnRemove.setText("Retirar");
btnRemove.setToolTipText("Retira dinero de tu cuenta");
btnRemove.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoveActionPerformed(evt);
}
});

btnDeposit.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N


btnDeposit.setMnemonic('D');
btnDeposit.setText("Depositar");
btnDeposit.setToolTipText("Deposita dienro en tu cuenta");
btnDeposit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDepositActionPerformed(evt);
}
});

btnBalance.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N


btnBalance.setMnemonic('D');
btnBalance.setText("Datos");
btnBalance.setToolTipText("Consulta saldo");
btnBalance.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBalanceActionPerformed(evt);
}
});

btnSearch.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N


btnSearch.setMnemonic('B');
btnSearch.setText("Buscar ");
btnSearch.setToolTipText("Busca el número de cuenta");
btnSearch.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSearchActionPerformed(evt);
}
});

jLabel1.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N


jLabel1.setText("Número de cuenta");

txtAcountNumber.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N


txtAcountNumber.setToolTipText("Digite su número de cuenta bancaria");
txtAcountNumber.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtAcountNumberActionPerformed(evt);
}
});
lblTitular.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
lblTitular.setText("Titular:");

lblBalance.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N


lblBalance.setText("Saldo:");

jLabel2.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N


jLabel2.setText("Cantidad:");

lblNewBalance.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N


lblNewBalance.setText("Nuevo saldo: ");

txtAmount.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N


txtAmount.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
txtAmount.setText("0");

javax.swing.GroupLayout layout = new


javax.swing.GroupLayout(getContentPane());
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, 127,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(jLabel2))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtAmount,
javax.swing.GroupLayout.PREFERRED_SIZE, 127,
javax.swing.GroupLayout.PREFERRED_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.DEFAULT_SIZE, 117, Short.MAX_VALUE)
.addComponent(btnBalance,
javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(btnDeposit,
javax.swing.GroupLayout.Alignment.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.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(btnRemove,
javax.swing.GroupLayout.PREFERRED_SIZE, 70,
javax.swing.GroupLayout.PREFERRED_SIZE)))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnSearch)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 43,
Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILI
NG)
.addGroup(layout.createSequentialGroup()
.addComponent(lblTitular)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27,
Short.MAX_VALUE)
.addComponent(lblBalance))
.addComponent(btnDeposit,
javax.swing.GroupLayout.PREFERRED_SIZE, 70,
javax.swing.GroupLayout.PREFERRED_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, 70,
javax.swing.GroupLayout.PREFERRED_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.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblNewBalance)))
.addContainerGap(28, Short.MAX_VALUE))
);

pack();
setLocationRelativeTo(null);
}// </editor-fold>

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: " + card[index].getHeadline().getName());
lblBalance.setText("Saldo: " + card[index].getBalance());
} else {
JOptionPane.showMessageDialog(this, "El número de cuenta digitado
no existe");
}
}

private void 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 saldo: " + card[index].getBalance());

} else {
JOptionPane.showMessageDialog(this, "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) {


card[index].remove(Float.parseFloat(txtAmount.getText()));
lblNewBalance.setText("Nuevo saldo: " + card[index].getBalance());

} else {
JOptionPane.showMessageDialog(this, "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, "El número de cuenta digitado
no existe");
}

private void txtAcountNumberActionPerformed(java.awt.event.ActionEvent


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 */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code
(optional) ">
/* 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(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
.SEVERE, null, ex);
} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(Atm.class.getName()).log(java.util.logging.Level
.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(Atm.class.getName()).log(java.util.logging.Level
.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */


java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Atm().setVisible(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 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 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 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, 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
*
* @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)) {
return Arrays.asList(t).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")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

btnRemove = new javax.swing.JButton();


btnDeposit = new javax.swing.JButton();
btnBalance = new javax.swing.JButton();
btnSearch = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
txtAcountNumber = new javax.swing.JTextField();
lblTitular = new javax.swing.JLabel();
lblBalance = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
lblNewBalance = new javax.swing.JLabel();
txtAmount = new javax.swing.JTextField();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Cajero ATM");

btnRemove.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N


btnRemove.setMnemonic('R');
btnRemove.setText("Retirar");
btnRemove.setToolTipText("Retira dinero de tu cuenta");
btnRemove.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoveActionPerformed(evt);
}
});

btnDeposit.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N


btnDeposit.setMnemonic('D');
btnDeposit.setText("Depositar");
btnDeposit.setToolTipText("Deposita dienro en tu cuenta");
btnDeposit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDepositActionPerformed(evt);
}
});

btnBalance.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N


btnBalance.setMnemonic('D');
btnBalance.setText("Datos");
btnBalance.setToolTipText("Consulta saldo");
btnBalance.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBalanceActionPerformed(evt);
}
});

btnSearch.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N


btnSearch.setMnemonic('B');
btnSearch.setText("Buscar ");
btnSearch.setToolTipText("Busca el número de cuenta");
btnSearch.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSearchActionPerformed(evt);
}
});

jLabel1.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N


jLabel1.setText("Número de cuenta");

txtAcountNumber.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N


txtAcountNumber.setToolTipText("Digite su número de cuenta bancaria");
txtAcountNumber.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtAcountNumberActionPerformed(evt);
}
});

lblTitular.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N


lblTitular.setText("Titular:");

lblBalance.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N


lblBalance.setText("Saldo:");

jLabel2.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N


jLabel2.setText("Cantidad:");

lblNewBalance.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N


lblNewBalance.setText("Nuevo saldo: ");

txtAmount.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N


txtAmount.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
txtAmount.setText("0");

javax.swing.GroupLayout layout = new


javax.swing.GroupLayout(getContentPane());
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, 127,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(jLabel2))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtAmount,
javax.swing.GroupLayout.PREFERRED_SIZE, 127,
javax.swing.GroupLayout.PREFERRED_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.DEFAULT_SIZE, 117, Short.MAX_VALUE)
.addComponent(btnBalance,
javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(btnDeposit,
javax.swing.GroupLayout.Alignment.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.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(btnRemove,
javax.swing.GroupLayout.PREFERRED_SIZE, 70,
javax.swing.GroupLayout.PREFERRED_SIZE)))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnSearch)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 43,
Short.MAX_VALUE)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILI
NG)
.addGroup(layout.createSequentialGroup()
.addComponent(lblTitular)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27,
Short.MAX_VALUE)
.addComponent(lblBalance))
.addComponent(btnDeposit,
javax.swing.GroupLayout.PREFERRED_SIZE, 70,
javax.swing.GroupLayout.PREFERRED_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, 70,
javax.swing.GroupLayout.PREFERRED_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.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblNewBalance)))
.addContainerGap(28, Short.MAX_VALUE))
);

pack();
setLocationRelativeTo(null);
}// </editor-fold>

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: " + card[index].getHeadline().getName());
lblBalance.setText("Saldo: " + card[index].getBalance());
} else {
JOptionPane.showMessageDialog(this, "El número de cuenta digitado no
existe");
}
}

private void 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) {


try { //Código que puede provocar errores
card[index].toDeposit(Float.parseFloat(txtAmount.getText()));
lblNewBalance.setText("Nuevo saldo: " + card[index].getBalance());
} catch (NumberFormatException ex) { //Gestión del error
NumberFormatException ex
JOptionPane.showMessageDialog(null, "Error no puede depositar esa
cantidad -->" + ex.getMessage());
}
} else {
JOptionPane.showMessageDialog(this, "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, "Error no puede retirar esa
cantidad -->" + ex.getMessage());
}

} else {
JOptionPane.showMessageDialog(this, "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, "El número de cuenta digitado no
existe");
}

private void txtAcountNumberActionPerformed(java.awt.event.ActionEvent 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 */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code
(optional) ">
/* 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(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
.SEVERE, null, ex);
} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(Atm.class.getName()).log(java.util.logging.Level
.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(Atm.class.getName()).log(java.util.logging.Level
.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */


java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Atm().setVisible(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 ayuda un tratamiento de excepciones que consiste
en un fragmento de código que permite capturar el error y dar una posible solución.
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 (excepciones no comprobadas). 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 básicas de Java. YouTube. Recuperado


de: https://www.youtube.com/watch?v=_ozU4ixNHo4

Reyes, G (2021). Ejemplo de una excepción. Tecnm.mx. Recuperado de:


https://tapachula.tecnm.mx/servicios/virtualroom/pluginfile.php/74243/mod_resourc
e/content/1/EjemploExcepciones.java

También podría gustarte