Examenhoy
Examenhoy
t: INTERFACES
----
GUI-PRINCIPAL
--------
protected void actionPerformedBtnProcesar(ActionEvent arg0) {
Gato g = new Gato();
listado(g);
if (x instanceof Gato) {
imprimir("vacuna A : S/ " + ((Gato) x).vacunaA);
imprimir("cuidado : " + ((Gato) x).cuidado());
}
else {
imprimir("vacuna A …
[5:13 p. m., 20/11/2023] Richie.t: package padre;
// Atributos protegidos
protected String nombre, apellido;
protected int edad;
// Constructor
public Persona(String nombre, String apellido, int edad) {
this.nombre = nombre;
this.apellido = apellido;
this.edad = edad;
}
// Operaciones p�blicas
public String datosCompletos() {
return "Nombre : " + nombre + "\n" +
"Apellido : " + apellido + "\n" +
"Edad : " + edad + "\n" +
"Correo : " + generarCorreo();
}
// Operaciones privadas
private String generarCorreo() {
return nombre + "." + apellido + "@cibertec.edu.pe";
}
HIJO
----
package hijos;
import padre.Persona;
// Atributos privados
private int horas;
private double tarifa;
// Constructor
public Docente(String nombre, String apellido, int edad,
int horas, double tarifa) {
super(nombre, apellido, edad);
this.horas = horas;
this.tarifa = tarifa;
}
// Operaciones p�blicas
public String datosCompletos() {
return super.datosCompletos() + "\n" +
"Horas : " + horas + "\n" +
"Tarifa : S/ " + tarifa + "\n" +
"sueldo : S/ " + calcularSueldo();
}
// Operaciones privadas
private double calcularSueldo() {
return horas * tarifa;
}
HIJO
--
package hijos;
import padre.Persona;
// Atributos privados
private int nota1, nota2, nota3;
// Constructor
public Alumno(String nombre, String apellido, int edad,
int nota1, int nota2, int nota3) {
super(nombre, apellido, edad);
this.nota1 = nota1;
this.nota2 = nota2;
this.nota3 = nota3;
}
// Operaciones p�blicas
public String datosCompletos() {
return super.datosCompletos() + "\n" +
"Nota1 : " + nota1 + "\n" +
"Nota2 : " + nota2 + "\n" +
"Nota3 : " + nota3 + "\n" +
"Promedio : " + calcularPromedio();
}
// Operaciones privadas
private double calcularPromedio() {
return (nota1 + nota2 + nota3) / 3.0;
}
}
GUI_PRINCIPAL
----------
ENUNCIADO
--------
Implemente en el paquete padre, la clase Vehiculo con los atributos protegidos de tipo
cadena: marca, modelo y placa, un constructor que inicialice los atributos, el método
datosDelVehiculo() que retorne en una cadena los dados del vehículo más un código
generado que se obtiene de concatenar marca, placa y modelo.
Implemente en el paquete hijos, la clase Auto que herede (usando extends) la clase padre
Vehiculo y agregue el atributo privado precio. A través del constructor reciba los cuatro
aributos y derive (usando super) los tres primeros a la clase padre Vehiculo. Implemente el
método público datosDelAuto() que retorne en una cadena los datos completos del auto
incluyendo el importe a pagar a través del método público aPagar() y considere que por
campaña cuenta con 10% de descuento.
Implemente en el paquete hijos, la clase Camioneta que herede (usando extends) la clase
padre Vehiculo y agregue el atributo privado precio. A través del constructor reciba los
cuatro atributos y derive (usando super) los tres primeros a la clase padre Vehiculo.
Implemente el método público datosDeLaCamioneta() que retorne en una cadena los
datos completos de la camioneta incluyendo el importe a pagar a través del método
público aPagar() y considere que por campaña cuenta con 20% de descuento.
A la pulsación del botón Procesar en la clase principal cree un objeto de tipo Vehiculo,
Auto y Camioneta respectivamente. Finalmente, visualice a través de tres métodos listado
la información completa de cada objeto.
Cambie la sintaxis de los métodos que retornan los datos completos de cada clase por el
de datosCompletos() y haga uso de super en las clases hijos para diferenciarlos.
Utilice un solo método listado que reciba como parámetro la referencia de la clase padre
Vehiculo, haga uso del operador instanceof para distinguir el tipo de objeto recibido y
visualice la información completa de los objetos.
import clase.Alumno;
import java.io.*;
import java.util.ArrayList;
import javax.swing.JOptionPane;
// Atributo privado
private ArrayList <Alumno> alu;
// Constructor
public ArregloAlumnos() {
alu = new ArrayList <Alumno> ();
cargarAlumnos();
}
// Operaciones p�blicas b�sicas
public void adicionar(Alumno x) {
alu.add(x);
// despues de agregar al arrray list , debe grabar
grabarAlumnos();
}
public int tamanio() {
return alu.size();
}
public Alumno obtener(int i) {
return alu.get(i);
}
public Alumno buscar(int codigo) {
for (int i=0; i<tamanio(); i++)
if (obtener(i).getCodigo() == codigo)
return obtener(i);
return null;
}
public void eliminar(Alumno x) {
alu.remove(x);
}
void grabarAlumnos() {
try {
PrintWriter pw;
pw= new PrintWriter(new FileWriter("alumnos.txt"));
String linea ;
//recorrer el arraylist
for (int i=0; i< tamanio(); i++) {
Alumno x = obtener(i);
// genera la linea a guardar
linea =x.getCodigo()+ ","+x.getNombre()+"," +
x.getNota1()+","+ x.getNota2();
// grabar la linea en el archivo y salta
pw.println(linea);
}
// cerrar el archivo
pw.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"error:"+
e.getMessage());
// TODO: handle exception
}
}
void cargarAlumnos() {
try {
// abre el archivo en modo de lectura
BufferedReader br;
br= new BufferedReader(new FileReader("alumnos.txt"));
String linea ;
//mientras haya lineas por leer en el archivo (!=null)
while ((linea = br.readLine()) !=null) {
//linea ="222,luis,12, 15"
//seprar linea
String [] datos = linea.split("\t");
// datos={"222","juan","18","15" }
// 0 1 2 3
int codigo =Integer.parseInt(datos[0]);
String nombre =datos[1];
int nota1 = Integer.parseInt(datos[2]);
int nota2 = Integer.parseInt(datos[3]);
// agregar al arrraylist (temporal)
alu.add(new Alumno (codigo,nombre,nota1, nota2));
}
// cerrar el archivo
br.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"error:"+
e.getMessage());
// TODO: handle exception
}
}
public void actualizarArchivo() {
grabarAlumnos();
}
CLASE
------
package arreglo;
import clase.Alumno;
import java.io.*;
import java.util.ArrayList;
import javax.swing.JOptionPane;
// Atributo privado
private ArrayList <Alumno> alu;
// Constructor
public ArregloAlumnos() {
alu = new ArrayList <Alumno> ();
cargarAlumnos();
}
// Operaciones p�blicas b�sicas
public void adicionar(Alumno x) {
alu.add(x);
// despues de agregar al arrray list , debe grabar
grabarAlumnos();
}
public int tamanio() {
return alu.size();
}
public Alumno obtener(int i) {
return alu.get(i);
}
public Alumno buscar(int codigo) {
for (int i=0; i<tamanio(); i++)
if (obtener(i).getCodigo() == codigo)
return obtener(i);
return null;
}
public void eliminar(Alumno x) {
alu.remove(x);
}
void grabarAlumnos() {
try {
PrintWriter pw;
pw= new PrintWriter(new FileWriter("alumnos.txt"));
String linea ;
//recorrer el arraylist
for (int i=0; i< tamanio(); i++) {
Alumno x = obtener(i);
// genera la linea a guardar
linea =x.getCodigo()+ ","+x.getNombre()+"," +
x.getNota1()+","+ x.getNota2();
// grabar la linea en el archivo y salta
pw.println(linea);
}
// cerrar el archivo
pw.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"error:"+
e.getMessage());
// TODO: handle exception
}
}
void cargarAlumnos() {
try {
// abre el archivo en modo de lectura
BufferedReader br;
br= new BufferedReader(new FileReader("alumnos.txt"));
String linea ;
//mientras haya lineas por leer en el archivo (!=null)
while ((linea = br.readLine()) !=null) {
//linea ="222,luis,12, 15"
//seprar linea
String [] datos = linea.split("\t");
// datos={"222","juan","18","15" }
// 0 1 2 3
int codigo =Integer.parseInt(datos[0]);
String nombre =datos[1];
int nota1 = Integer.parseInt(datos[2]);
int nota2 = Integer.parseInt(datos[3]);
// agregar al arrraylist (temporal)
alu.add(new Alumno (codigo,nombre,nota1, nota2));
}
// cerrar el archivo
br.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"error:"+
e.getMessage());
// TODO: handle exception
}
}
public void actualizarArchivo() {
grabarAlumnos();
GUI-PRINCIPAL
-----------
protected void actionPerformedBtnAdicionar(ActionEvent arg0) {
/**
* Adiciona un nuevo alumno validando que el c�digo no se repita
*/
try {
int codigo = leerCodigo();
if (aa.buscar(codigo) == null) {
String nombre = leerNombre();
if (nombre.length() > 0)
try {
int nota1 = leerNota1();
try {
int nota2 = leerNota2();
Alumno nuevo = new Alumno(codigo,
nombre, nota1, nota2);
aa.adicionar(nuevo);
listar();
limpieza();
}
catch (Exception e) {
error("ingrese NOTA 2", txtNota2);
}
}
catch (Exception e) {
error("ingrese NOTA 1", txtNota1);
}
else
error("ingrese NOMBRE", txtNombre);
}
else
error("el CÓDIGO ya existe", txtCodigo);
}
catch (Exception e) {
error("ingrese CÓDIGO", txtCodigo);
}
}
protected void actionPerformedBtnConsultar(ActionEvent arg0) {
/**
* Busca un c�digo y si existe muestra los datos del alumno
*/
try {
int codigo = leerCodigo();
Alumno a = aa.buscar(codigo);
if (a == null) {
mensaje("el CÓDIGO no existe");
limpieza();
}
else {
txtNombre.setText(a.getNombre());
txtNota1.setText("" + a.getNota1());
txtNota2.setText("" + a.getNota2());
txtCodigo.requestFocus();
}
}
catch (Exception e) {
mensaje("ingrese CÓDIGO");
limpieza();
}
}
protected void actionPerformedBtnModificar(ActionEvent arg0) {
/**
* Modifica los datos de un alumnno
*/
try {
int codigo = leerCodigo();
Alumno x = aa.buscar(codigo);
if (x != null) {
String nombre = leerNombre();
if (nombre.length() > 0)
try {
int nota1 = leerNota1();
try {
int nota2 = leerNota2();
x.setCodigo(codigo);
x.setNombre(nombre);
x.setNota1(nota1);
x.setNota2(nota2);
aa.actualizarArchivo();
listar();
limpieza();
}
catch (Exception e) {
error("ingrese NOTA 2", txtNota2);
}
}
catch (Exception e) {
error("ingrese NOTA 1", txtNota1);
}
else
error("ingrese NOMBRE", txtNombre);
}
else
error("el CÓDIGO no existe", txtCodigo);
}
catch (Exception e) {
error("ingrese CÓDIGO", txtCodigo);
}
}
protected void actionPerformedBtnEliminar(ActionEvent arg0) {
/**
* Busca un codigo y si existe retira al alumno del arreglo
*/
try {
int codigo = leerCodigo();
Alumno a = aa.buscar(codigo);
if (a == null)
mensaje("el C�DIGO no existe");
else {
aa.eliminar(a);
listar();
}
limpieza();
}
catch (Exception e) {
error("ingrese C�DIGO", txtCodigo);
}
}
// M�todos tipo void (sin par�metros)
void limpieza() {
txtCodigo.setText("");
txtNombre.setText("");
txtNota1.setText("");
txtNota2.setText("");
txtCodigo.requestFocus();
}
void listar() {
modelo.setRowCount(0);
for (int i=0; i<aa.tamanio(); i++) {
Object[] fila = { aa.obtener(i).getCodigo(),
aa.obtener(i).getNombre(),
aa.obtener(i).getNota1(),
aa.obtener(i).getNota2(),
aa.obtener(i).promedio() };
modelo.addRow(fila);
}
}
// M�todos tipo void (con par�metros)
void mensaje(String s) {
JOptionPane.showMessageDialog(this, s);
}
void error(String s, JTextField txt) {
mensaje(s);
txt.setText("");
txt.requestFocus();
}
// M�todos que retornan valor (sin par�metros)
int leerCodigo() {
return Integer.parseInt(txtCodigo.getText().trim());
}
String leerNombre() {
return txtNombre.getText().trim();
}
int leerNota1() {
return Integer.parseInt(txtNota1.getText().trim());
}
int leerNota2() {
return Integer.parseInt(txtNota2.getText().trim());
}