🦄💫4° SEM32 WORD PLANEACIÓN PROYECTOS DARUKEL 23-24.docx
Java HashMap
1. Desarrollar un sistema de gestión de partes de un taller mecánico.
La información de los partes es: código, descripción e importe. Un parte irá asociado a la matrícula de un coche de
manera que podamos añadir, mostrar y eliminar un parte a partir de la matrícula de coche al que está asociado. La
información de una matrícula es: provincia, número y letra.
La clase Practica11d mostrará un menú de opciones por consola: crear, listar, mostrar y eliminar partes. También
habrá una opción de salir.
El formato de entrada de una matrícula es: provincia-número-letra (por ejemplo: M-1234-AV).
Para leer por teclado se usará la clase Lector que se adjunta con esta práctica.
Realizar el diagrama UML.
Lector.java
/*
* @(#)Lector.java 1.1 27-Nov-2004
*
* Copyright (c) 2004 José M. Ordax. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the MIT License
* which accompanies this distribution, and is available at
* http://www.opensource.org/licenses/mit-license.html
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* La clase <code>Lector</code> sirve para leer datos de distintos
* tipos por el teclado. Posee un método estático para leer cada tipo.
* <p><p/>
* Un ejemplo de su uso sería:
* <blockquote><pre>
* System.out.println("Introduzca un String: ");
* String unString = Lector.leerString();
* System.out.println("El String introducido es: " + unString);
* </pre></blockquote>
* <p>
* Al realizar operaciones de entrada/salida o conversiones entre tipos
* se pueden producir problemas (excepciones en la tecnología Java) como
* por ejemplo {@link java.lang.NumberFormatException} o
* {@link java.io.IOException}.
* Todos estos problemas están controlados y gestionados por la clase
* <code>Lector</code> y en caso de producirse, se mostrará un mensaje
* de error por pantalla explicando el motivo.
*
* @author José M. Ordax
* @version 1.1, 27-Nov-2004
* @see java.lang.System#in
* @see java.io.InputStream
* @see java.io.InputStreamReader
* @see java.io.BufferedReader
* @see java.io.IOException
*/
bitCoach::Juan Bautista Cascallar Lorenzo
2. public class Lector
{
// Atributos.
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Constructor.
private Lector()
{
super();
}
/**
* Lee un byte por teclado. Utiliza la tecla "Enter" para indicar el final del dato.
*
* @return el byte introducido o 0 si se produjo algún problema.
*/
public static byte leerByte()
{
byte tmp = 0;
try
{
tmp = Byte.parseByte(br.readLine());
}
catch (NumberFormatException ex)
{
System.out.println("Error: el dato introducido no se puede convertir en un byte.");
ex.printStackTrace();
}
catch (IOException ex)
{
System.out.println("Error: hubo un problema en la operación de entrada de datos.");
ex.printStackTrace();
}
catch(Exception ex)
{
System.out.println("Error: hubo un problema no controlado.");
ex.printStackTrace();
}
return tmp;
}
/**
* Lee un short por teclado. Utiliza la tecla "Enter" para indicar el final del dato.
*
* @return el short introducido o 0 si se produjo algún problema.
*/
public static short leerShort()
{
short tmp = 0;
try
{
tmp = Short.parseShort(br.readLine());
}
catch (NumberFormatException ex)
{
System.out.println("Error: el dato introducido no se puede convertir en un short.");
ex.printStackTrace();
}
catch (IOException ex)
{
System.out.println("Error: hubo un problema en la operación de entrada de datos.");
ex.printStackTrace();
}
catch(Exception ex)
{
System.out.println("Error: hubo un problema no controlado.");
ex.printStackTrace();
}
return tmp;
}
bitCoach::Juan Bautista Cascallar Lorenzo
3. /**
* Lee un char por teclado. Utiliza la tecla "Enter" para indicar el final del dato.
*
* @return el primer char introducido o un blanco si se produjo algún problema.
*/
public static char leerChar()
{
char tmp = ' ';
try
{
tmp = br.readLine().charAt(0);
}
catch (IOException ex)
{
System.out.println("Error: hubo un problema en la operación de entrada de datos.");
ex.printStackTrace();
}
catch(Exception ex)
{
System.out.println("Error: hubo un problema no controlado.");
ex.printStackTrace();
}
return tmp;
}
/**
* Lee un int por teclado. Utiliza la tecla "Enter" para indicar el final del dato.
*
* @return el int introducido o 0 si se produjo algún problema.
*/
public static int leerInt()
{
int tmp = 0;
try
{
tmp = Integer.parseInt(br.readLine());
}
catch (NumberFormatException ex)
{
System.out.println("Error: el dato introducido no se puede convertir en un int.");
ex.printStackTrace();
}
catch (IOException ex)
{
System.out.println("Error: hubo un problema en la operación de entrada de datos.");
ex.printStackTrace();
}
catch(Exception ex)
{
System.out.println("Error: hubo un problema no controlado.");
ex.printStackTrace();
}
return tmp;
}
/**
* Lee un long por teclado. Utiliza la tecla "Enter" para indicar el final del dato.
*
* @return el long introducido o 0 si se produjo algún problema.
*/
public static long leerLong()
{
long tmp = 0;
try
{
tmp = Long.parseLong(br.readLine());
}
catch (NumberFormatException ex)
{
System.out.println("Error: el dato introducido no se puede convertir en un long.");
ex.printStackTrace();
}
catch (IOException ex)
{
System.out.println("Error: hubo un problema en la operación de entrada de datos.");
ex.printStackTrace();
}
catch(Exception ex)
{
System.out.println("Error: hubo un problema no controlado.");
ex.printStackTrace();
}
return tmp;
}
bitCoach::Juan Bautista Cascallar Lorenzo
4. /**
* Lee un float por teclado. Utiliza la tecla "Enter" para indicar el final del dato.
*
* @return el float introducido o 0.0 si se produjo algún problema.
*/
public static float leerFloat()
{
float tmp = 0;
try
{
tmp = Float.parseFloat(br.readLine());
}
catch (NumberFormatException ex)
{
System.out.println("Error: el dato introducido no se puede convertir en un float.");
ex.printStackTrace();
}
catch (IOException ex)
{
System.out.println("Error: hubo un problema en la operación de entrada de datos.");
ex.printStackTrace();
}
catch(Exception ex)
{
System.out.println("Error: hubo un problema no controlado.");
ex.printStackTrace();
}
return tmp;
}
/**
* Lee un double por teclado. Utiliza la tecla "Enter" para indicar el final del dato.
*
* @return el double introducido o 0.0 si se produjo algún problema.
*/
public static double leerDouble()
{
double tmp = 0;
try
{
tmp = Double.parseDouble(br.readLine());
}
catch (NumberFormatException ex)
{
System.out.println("Error: el dato introducido no se puede convertir en un
double.");
ex.printStackTrace();
}
catch (IOException ex)
{
System.out.println("Error: hubo un problema en la operación de entrada de datos.");
ex.printStackTrace();
}
catch(Exception ex)
{
System.out.println("Error: hubo un problema no controlado.");
ex.printStackTrace();
}
return tmp;
}
/**
* Lee una cadena de caracteres por teclado. Utiliza la tecla "Enter" para indicar el final del dato.
*
* @return el string introducido o <code>null</code> si se produjo algún problema.
*/
public static String leerString()
{
String tmp = null;
try
{
tmp = br.readLine();
}
catch (IOException ex)
{
System.out.println("Error: hubo un problema en la operación de entrada de datos.");
ex.printStackTrace();
}
catch(Exception ex)
{
System.out.println("Error: hubo un problema no controlado.");
ex.printStackTrace();
}
return tmp;
}
bitCoach::Juan Bautista Cascallar Lorenzo
5. /**
* Lee un boolean por teclado. Utiliza la tecla "Enter" para indicar el final del dato.
*
* @return <code>false</code> en cualquier caso a no ser que se introduzca la cadena "true".
*/
public static boolean leerBoolean()
{
boolean tmp = false;
try
{
tmp = new Boolean(br.readLine()).booleanValue();
}
catch (IOException ex)
{
System.out.println("Error: hubo un problema en la operación de entrada de datos.");
ex.printStackTrace();
}
catch(Exception ex)
{
System.out.println("Error: hubo un problema no controlado.");
ex.printStackTrace();
}
return tmp;
}
}
CodigosParte.java
public class CodigosParte {
public static int codigo = 1;
}
Matricula.java
public class Matricula {
//Atributos
private String provincia;
private int numero;
private String letra;
//Constructor
public Matricula(String prov, int num, String letr){
provincia = prov;
numero = num;
letra = letr;
}
public boolean equals(Object o){
if(this == o){
return true;
}
if(!(o instanceof Matricula)){
return false;
}
Matricula param = (Matricula)o;
return param.provincia.equals(provincia) && param.numero == numero &&
param.letra.equals(letra);
}
public int hashCode(){
StringBuffer buffer = new StringBuffer();
buffer.append(provincia);
buffer.append(Integer.toString(numero));
buffer.append(letra);
return buffer.toString().hashCode();
}
bitCoach::Juan Bautista Cascallar Lorenzo
6. //Getters
public String getProvincia(){
return provincia;
}
public int getNumero(){
return numero;
}
public String getLetra(){
return letra;
}
}
Parte.java
public class Parte {
//Atributos
private Matricula matricula;
private int codigo;
private String descripcion;
double importe = 0.0;
//Constructor
public Parte(Matricula matric, String desc, double imp){
codigo = CodigosParte.codigo;
matricula = matric;
descripcion = desc;
importe = imp;
}
//GETTERS
public int getCodigo(){
return codigo;
}
public Matricula getMatricula(){
return matricula;
}
public String getDescripcion(){
return descripcion;
}
public double getImporte(){
return importe;
}
}
GestorPartesHMap.java
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
public class GestorPartesHMap {
//Atributos
HashMap<Matricula,ArrayList<Parte>> hm = new HashMap<Matricula,ArrayList<Parte>>();
//--- OPCIÓN [1]: CREAR PARTE ---
public void crearParte(){
Parte p;
System.out.println("DATOS PARA CREAR EL PARTE ");
System.out.println("------------------------------------------");
Matricula m = crearMatricula();
System.out.println("DESCRIPCIÓN: ");
String descripcion = Lector.leerString();
System.out.println("IMPORTE: ");
double importe = Lector.leerDouble();
p = new Parte(m,descripcion,importe);
bitCoach::Juan Bautista Cascallar Lorenzo
7. if(hm.containsKey(p.getMatricula()) == false){
ArrayList<Parte> partes = new ArrayList<Parte>();
hm.put(p.getMatricula(), partes);
hm.get(p.getMatricula()).add(p);
}else{
hm.get(p.getMatricula()).add(p);
}
CodigosParte.codigo++;
}
//--- OPCIÓN [2]: LISTAR PARTES POR COCHE ---
public void listarPartesPorCoche(){
System.out.println("LISTAR PARTES POR COCHE/MATRICULA: ");
System.out.println("------------------------------------------");
Matricula m = crearMatricula();
if(hm.containsKey(m) == true){
ArrayList<Parte> partes = hm.get(m);
Iterator<Parte> it = partes.iterator();
System.out.println("Partes asociados a la matrícula [" + m.getProvincia() +
"-" + m.getNumero() + "-" + m.getLetra() + "]");
System.out.println("===================================================");
while(it.hasNext()){
Parte p = it.next();
System.out.println("-----------------------------------");
System.out.println("MATRÍCULA: " + p.getMatricula().getProvincia()+
"-" + p.getMatricula().getNumero() + "-" +
p.getMatricula().getLetra());
System.out.println("CÓDIGO: " + p.getCodigo());
System.out.println("DESCRIPCIÓN: " + p.getDescripcion());
System.out.println("PRECIO: " + p.getImporte());
System.out.println("-----------------------------------");
}
}else{
System.out.println("Objeto no localizado...");
}
}//fin funcion
//--- OPCIÓN [3]: LISTADO COMPLETO DE PARTES ---
public void listadoCompletoDePartes(){
if(hm.size() != 0){
Set<Matricula> claves = hm.keySet();
Iterator<Matricula> itClaves = claves.iterator();
while(itClaves.hasNext())
{
Matricula m = itClaves.next();
System.out.println("Partes asociados a la matricula: " +
m.getProvincia() + "-" + m.getNumero() + "-" + m.getLetra());
System.out.println("---------------------------------------------------");
ArrayList<Parte> partes = hm.get(m);
Iterator<Parte> itPartes = partes.iterator();
while(itPartes.hasNext()){
Parte p = itPartes.next();
System.out.println("-----------------------------------");
System.out.println("MATRICULA: " + p.getMatricula().getProvincia() +
"-" + p.getMatricula().getNumero() + "-" +
p.getMatricula().getLetra());
System.out.println("CÓDIGO: " + p.getCodigo());
System.out.println("DESCRIPCIÓN: " + p.getDescripcion());
System.out.println("IMPORTE: " + p.getImporte());
System.out.println("-----------------------------------");
}
}
}else{
System.out.println("No hay partes....");
}
}//fin funcion
bitCoach::Juan Bautista Cascallar Lorenzo
8. //--- [4] ELIMINAR PARTE POR MATRICULA ---
public void eliminarPartePorMatricula(){
Matricula m = crearMatricula();
if(hm.containsKey(m) == true){
ArrayList<Parte> partes = hm.get(m);
Iterator<Parte> it = partes.iterator();
System.out.println("Partes asociados a la matrícula [" + m.getProvincia() +
"-" + m.getNumero() + "-" + m.getLetra() + "]");
System.out.println("===================================================");
while(it.hasNext()){
Parte p = it.next();
System.out.println("-----------------------------------");
System.out.println("MATRÍCULA: " + p.getMatricula().getProvincia()+
"-" + p.getMatricula().getNumero() + "-" +
p.getMatricula().getLetra());
System.out.println("CÓDIGO: " + p.getCodigo());
System.out.println("DESCRIPCIÓN: " + p.getDescripcion());
System.out.println("PRECIO: " + p.getImporte());
System.out.println("-----------------------------------");
}
System.out.println("Código del Parte que quieres borrar: ");
int codigo = Lector.leerInt();
Iterator<Parte> it2 = partes.iterator();
while(it2.hasNext()){
Parte p = it2.next();
if(codigo == p.getCodigo()){
it2.remove();
System.out.println("Parte eliminado....");
}else{
System.out.println("Objeto no encontrado...");
}
}
}else{
System.out.println("Objeto no localizado...");
}
}//fin funcion
//--- [5] ELIMINAR TODOS LOS PARTES ASOCIADOS A UNA MATRICULA ---
public void eliminarTodosLosPartesPorMatricula(){
Matricula m = crearMatricula();
if(hm.containsKey(m) == true){
hm.remove(m);
System.out.println("Se han borrado todos los partes asociados a la matricula: " +
m.getProvincia() + "-" + m.getNumero() + "-" + m.getLetra());
}else{
System.out.println("Objeto no encontrado...");
}
}
private Matricula crearMatricula(){
System.out.println("MATRICULA DEL COCHE (PROVINCIA-NÚMERO-LETRA):");
//-- Leer matrícula ---
String provincia,letra;
int numero;
//--- PROVINCIA ---
boolean correcto = true;
do{
correcto = true;
System.out.println("PROVINCIA: "); provincia = Lector.leerString();
for(int i=0;i<provincia.length();i++){
if(Character.isLetter(provincia.charAt(i)) == false){
System.out.println("El campo <PROVINCIA> sólo contiene letras...");
correcto = false;
break;
}
}
}while(correcto == false);
//---
bitCoach::Juan Bautista Cascallar Lorenzo
9. //--- NUMERO ---
System.out.println("NÚMERO: "); numero = Lector.leerInt();
//--- LETRA ---
correcto = true;
do{
correcto = true;
System.out.println("LETRA: "); letra = Lector.leerString();
for(int i=0;i<letra.length();i++){
if(Character.isLetter(letra.charAt(i)) == false){
System.out.println("El campo <LETRA> sólo contiene letras...");
correcto = false;
break;
}
}
}while(correcto == false);
//---
Matricula m = new Matricula(provincia,numero,letra);
return m;
}
}//FIN CLASE
TestGestionPartes.java
public class TestGestionPartes {
/**
* @param args
*/
//Atributos
private static GestorPartesHMap gp = new GestorPartesHMap();
public static void main(String[] args) {
// TODO Auto-generated method stub
//MENÚ (SELECCIONAR OPCIÓN)
int seleccion = 0;
do{
System.out.println("SELECCIONA LA OPCIÓN DE MENÚ............");
System.out.println("[1] CREAR PARTE");
System.out.println("[2] LISTADO DE PARTES POR MATRICULA");
System.out.println("[3] LISTADO COMPLETO DE PARTES");
System.out.println("[4] ELIMINAR PARTE POR MATRICULA");
System.out.println("[5] ELIMINAR TODOS LOS PARTES ASOCIADOS A UNA MATRICULA");
System.out.println("[6] SALIR");
System.out.println("Selection: ");
seleccion = Lector.leerInt();
//-------------
switch (seleccion){
case 1: gp.crearParte(); break;
case 2: gp.listarPartesPorCoche(); break;
case 3: gp.listadoCompletoDePartes(); break;
case 4: gp.eliminarPartePorMatricula(); break;
case 5: gp.eliminarTodosLosPartesPorMatricula(); break;
case 6: System.out.println("Fin del programa.");System.exit(0);
default: System.out.println("Teclea una opción válida"); break;
}//Fin switch
}while(seleccion!=6);//Fin while
}//Fin main
}//Fin clase
bitCoach::Juan Bautista Cascallar Lorenzo