Java - Java. Ayuda con este ejercicio

 
Vista:

Java. Ayuda con este ejercicio

Publicado por Alfonso (1 intervención) el 18/01/2019 03:55:27
Necesito realizar este ejercicio pero no tengo idea como hacerlo.

Considere la clase Artefacto, con los siguientes atributos:
- marca: string (no acepta números, sin espacios y en mayúscula).
- modelo: string (acepta hasta 5 letras y hasta 3 números).
- año: integer (de 4 dígitos, positivo, menor a 2015).

Y 2 clases hijas:
Televisor
Atributos:
- tamaño: integer (se refiere a las pulgadas. De hasta 3 dígitos, positivo).
- emp_cable: string (no acepta números, sin espacio, y en minúscula).
Radio
Atributos:
- num_parlantes: integer (de hasta 1 dígito, positivo).
- freq_radio_1: float (de 1 decimal, positivo, hasta 108,3).
- freq_radio_2: float (de 1 decimal, positivo, hasta 108,3, distinto a freq_radio_1).

Cree un programa en Java que muestre un menú con las opciones de ingresar los datos de un Televisor o de una Radio, y maneje las excepciones mediante clases, métodos y try/catch dependiendo del dato que se está validando.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Billy Joel
Val: 2.665
Oro
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

Java. Ayuda con este ejercicio

Publicado por Billy Joel (876 intervenciones) el 18/01/2019 20:27:34
Yo lo resuelvo así...
La clase Artefacto
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class Artefacto {
    private String marca;
    private String modelo;
    private String año;
 
    /**
     * @return the marca
     */
    public String getMarca() {
        return marca;
    }
 
    /**
     * @param marca the marca to set
     */
    public void setMarca(String marca) {
        this.marca = marca;
    }
 
    /**
     * @return the modelo
     */
    public String getModelo() {
        return modelo;
    }
 
    /**
     * @param modelo the modelo to set
     */
    public void setModelo(String modelo) {
        this.modelo = modelo;
    }
 
    /**
     * @return the año
     */
    public String getAño() {
        return año;
    }
 
    /**
     * @param año the año to set
     */
    public void setAño(String año) {
        this.año = año;
    }
}

Las clases Televisor y Radio heredan (extends) de Artefacto
La clase Televisor:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Televisor extends Artefacto{
    private Integer tamaño;
    private String empCable;
 
    /**
     * @return the tamaño
     */
    public Integer getTamaño() {
        return tamaño;
    }
 
    /**
     * @param tamaño the tamaño to set
     */
    public void setTamaño(Integer tamaño) {
        this.tamaño = tamaño;
    }
 
    /**
     * @return the empCable
     */
    public String getEmpCable() {
        return empCable;
    }
 
    /**
     * @param empCable the empCable to set
     */
    public void setEmpCable(String empCable) {
        this.empCable = empCable;
    }
}

La clase Radio
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class Radio extends Artefacto{
 
    private Integer numParlantes;
    private float freqRadio1;
    private float freqRadio2;
 
    /**
     * @return the numParlantes
     */
    public Integer getNumParlantes() {
        return numParlantes;
    }
 
    /**
     * @param numParlantes the numParlantes to set
     */
    public void setNumParlantes(Integer numParlantes) {
        this.numParlantes = numParlantes;
    }
 
    /**
     * @return the freqRadio1
     */
    public float getFreqRadio1() {
        return freqRadio1;
    }
 
    /**
     * @param freqRadio1 the freqRadio1 to set
     */
    public void setFreqRadio1(float freqRadio1) {
        this.freqRadio1 = freqRadio1;
    }
 
    /**
     * @return the freqRadio2
     */
    public float getFreqRadio2() {
        return freqRadio2;
    }
 
    /**
     * @param freqRadio2 the freqRadio2 to set
     */
    public void setFreqRadio2(float freqRadio2) {
        this.freqRadio2 = freqRadio2;
    }
}

Entonces la clase principal:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
//import java.util.ArrayList;
import java.util.HashMap;
//import java.util.List;
import java.util.Map;
 
public class ProgramaPrincipal {
 
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//    List<Character> numeros = new ArrayList();
    char [] numeros = {'1','2','3','4','5','6','7','8','9','0'};
 
    Map<String, Televisor> televisores = new HashMap();
    Map<String, Radio> radios = new HashMap();
 
    public ProgramaPrincipal() {
//        numeros.add('1');
//        numeros.add('2');
//        numeros.add('3');
//        numeros.add('4');
//        numeros.add('5');
//        numeros.add('6');
//        numeros.add('7');
//        numeros.add('8');
//        numeros.add('9');
//        numeros.add('0');
    }
 
    /**
     * Metodo utilizado para leer un String
     *
     * @param message
     * @return
     */
    private static String leerString(String message) {
        String r = null;
        try {
            System.out.print(message);
            r = br.readLine();
        } catch (IOException ex) {
            System.out.println("Hubo un error de lectura");
        }
        return r;
    }
 
    /**
     * Metodo utilizado para leer un entero
     *
     * @param message
     * @return
     */
    private static Integer leerInt(String message) {
        Integer i = null;
        try {
            i = Integer.parseInt(leerString(message));
        } catch (NumberFormatException ex) {
            System.out.println("Hubo un error de lectura. Vuelva a intentarlo");
        }
        return i == null ? leerInt(message) : i;
    }
 
    /**
     * Metodo utilizado para leer un flotante
     *
     * @param message
     * @return
     */
    private static Float leerFloat(String message) {
        Float i = null;
        try {
            i = Float.parseFloat(leerString(message));
        } catch (NumberFormatException ex) {
            System.out.println("Hubo un error de lectura. Vuelva a intentarlo");
        }
        return i == null ? leerFloat(message) : i;
    }
 
    /**
     * Metodo utilizado para leer un entero con un rango dado
     *
     * @param message
     * @param min
     * @param max
     * @return
     */
    private static Integer leerIntConRango(String message, int min, int max) {
        Integer i;
        i = leerInt(message);
        if (i < min || i > max) {
            System.out.println("Número fuera del rango permitido que es desde " + min + " a " + max + ". Vuelva a intentarlo");
            i = leerIntConRango(message, min, max);
        }
        return i;
    }
 
    private Artefacto ingresarArtefacto() {
        Artefacto a = new Artefacto();
        String aux;
        //Marca
        aux = leerString("Introduzca la marca: ");
        if (aux.contains(" ")) {
            System.out.println("No se permite espacios en blanco en la marca");
        } else if (hasNumeros(aux)) {
            System.out.println("No se permiten números en la marca");
        } else {
            a.setMarca(aux.toUpperCase());
        }
        if (a.getMarca().isEmpty()) {
            return null;
        }
 
        //Modelo
        aux = leerString("Introduzca el modelo: ");
        if (aux.length() > 5) {
            System.out.println("El modelo no puede tener mas de 5 caracteres");
        } else if (!hasMenos3Numeros(aux)) {
            System.out.println("El modelo no puede tener mas de 3 números");
        } else {
            a.setModelo(aux);
        }
        if (a.getModelo().isEmpty()) {
            return null;
        }
 
        //Año
        Integer año = leerInt("introduzca el año: ");
        if (año.toString().length() != 4) {
            System.out.println("El año debe tener 4 dígitos");
        } else if (año > 2015) {
            System.out.println("El año debe ser menor a 2015");
        } else if (año < 0) {
            System.out.println("El año debe ser positivo");
        } else {
            a.setAño(año.toString());
        }
        if (a.getAño().isEmpty()) {
            return null;
        }
 
        return a;
    }
 
    /**
     * Evalúa si el String contiene numeros
     *
     * @param s
     * @return
     */
    private boolean hasNumeros(String s) {
        boolean b = false;
        for (char c : s.toCharArray()) {
//            if (numeros.contains(c)) {
//                b = true;
//                break;
//            }
            for(char n : numeros){
                if(c == n){
                    b = true;
                    break;
                }
            }
        }
        return b;
    }
 
    private boolean hasMenos3Numeros(String s) {
        int contador = 0;
        for (char c : s.toCharArray()) {
//            if (numeros.contains(c)) {
//                contador++;
//            }
            for(char n : numeros){
                if(c == n){
                    contador++;
                }
            }
        }
        return contador <= 3;
    }
 
    /**
     * Metodo utilizado para ingresar televisore
     */
    public void ingresarTelevisor() {
        Artefacto artefacto = ingresarArtefacto();
        if (artefacto == null) {
            return;
        }
        Televisor t = new Televisor();
        t.setMarca(artefacto.getMarca());
        t.setModelo(artefacto.getModelo());
        t.setAño(artefacto.getAño());
        System.out.println();
 
        //Tamaño
        Integer tamaño = leerInt("Introduzca el tamaño: ");
        if (tamaño.toString().length() > 3) {
            System.out.println("El tamaño no puede mayor de 999");
        } else if (tamaño < 1) {
            System.out.println("El tamaño debe ser un número positivo");
        } else {
            t.setTamaño(tamaño);
        }
        if (t.getTamaño().toString().isEmpty()) {
            return;
        }
 
        String empCable = leerString("Introduzca emp_cable: ");
        if (hasNumeros(empCable)) {
            System.out.println("No se aceptan números");
        } else if (empCable.contains(" ")) {
            System.out.println("No se aceptan espacios en blanco");
        } else {
            t.setEmpCable(empCable.toLowerCase());
        }
        if (t.getEmpCable().isEmpty()) {
            return;
        }
 
        televisores.put(t.getModelo(), t);
 
    }
 
    /**
     * Metodo utilizado para ingresar radios
     */
    public void ingresarRadio() {
        Artefacto artefacto = ingresarArtefacto();
        if (artefacto == null) {
            return;
        }
        Radio r = new Radio();
        r.setMarca(artefacto.getMarca());
        r.setModelo(artefacto.getModelo());
        r.setAño(artefacto.getAño());
        System.out.println();
 
        //Numero de parlantes
        Integer numParlantes = leerInt("Introduzca el numero de parlantes: ");
        if (numParlantes < 1) {
            System.out.println("El numero de parlantes debe ser un número positivo");
        } else {
            r.setNumParlantes(numParlantes);
        }
        if (r.getNumParlantes().toString().isEmpty()) {
            return;
        }
 
        //freqRadio1
        Float freq = leerFloat("Introduzca la frecuencia de radio 1: ");
        if (freq < 0 || freq > 108.3) {
            System.out.println("La frecuencia debe ser un número flotante positivo y menor e igual que 108.3");
        } else {
            r.setFreqRadio1(freq);
        }
        if (r.getFreqRadio1() == 0) {
            return;
        }
        freq = leerFloat("Introduzca la frecuencia de radio 2: ");
        if (freq < 0 || freq > 108.3) {
            System.out.println("La frecuencia debe ser un número flotante positivo y menor e igual que 108.3");
        } else if (freq == r.getFreqRadio1()) {
            System.out.println("La frecuencia 2 no debe ser igual a la frecuencia 1");
        } else {
            r.setFreqRadio1(freq);
        }
        if (r.getFreqRadio2() == 0) {
            return;
        }
 
        radios.put(r.getModelo(), r);
    }
 
    public void listarArtefactos(){
        listarTelevisores();
        listarRadios();
    }
 
    public void listarTelevisores(){
        System.out.println("A continuación los televisores:");
        televisores.forEach((k,v)->{
            System.out.println("Marca: " + v.getMarca());
            System.out.println("Modelo: " + k);
            System.out.println("Año: " + v.getAño());
            System.out.println("Tamaño: " + v.getTamaño());
            System.out.println("Emp_cable: " + v.getEmpCable());
            System.out.println("-----------------------------------------------");
        });
    }
 
    public void listarRadios(){
        System.out.println("A continuación las Radios:");
        radios.forEach((k,v)->{
            System.out.println("Marca: " + v.getMarca());
            System.out.println("Modelo: " + k);
            System.out.println("Año: " + v.getAño());
            System.out.println("Numero parlantes: " + v.getNumParlantes());
            System.out.println("Frecuencia 1: " + v.getFreqRadio1());
            System.out.println("Frecuencia 2: " + v.getFreqRadio2());
            System.out.println("-----------------------------------------------");
        });
    }
 
    public static final int OPCION_SALIR = 0;
    public static final int OPCION_INGRESAR_TELEVISOR = 1;
    public static final int OPCION_INGRESAR_RADIO = 2;
    public static final int OPCION_LISTAR_ARTEFACTOS = 3;
    public static final int OPCION_LISTAR_TELEVISORES = 4;
    public static final int OPCION_LISTAR_RADIO = 5;
 
    public static void main(String[] args) {
        ProgramaPrincipal p = new ProgramaPrincipal();
        int opcion = -1;
        while (opcion != OPCION_SALIR) {
            opcion = leerIntConRango("Introduzca " + OPCION_SALIR + " para salir"
                    + "\nIntroduzca " + OPCION_INGRESAR_TELEVISOR + " para ingresar un televisor "
                    + "\nIntroduzca " + OPCION_INGRESAR_RADIO + " para ingresar un radio "
                    + "\nIntroduzca " + OPCION_LISTAR_ARTEFACTOS + " para listar todos los artefactos"
                    + "\nIntroduzca " + OPCION_LISTAR_TELEVISORES + " para listar los televisores"
                    + "\nIntroduzca " + OPCION_LISTAR_RADIO + " para listar los radio: ",
                    OPCION_SALIR, OPCION_LISTAR_RADIO);
            switch (opcion) {
                case OPCION_SALIR:
                    System.out.println("Adios...");
                    break;
                case OPCION_INGRESAR_TELEVISOR:
                    p.ingresarTelevisor();
                    break;
                case OPCION_INGRESAR_RADIO:
                    p.ingresarRadio();
                    break;
                case OPCION_LISTAR_ARTEFACTOS:
                    p.listarArtefactos();
                    break;
                case OPCION_LISTAR_TELEVISORES:
                    p.listarTelevisores();
                    break;
                case OPCION_LISTAR_RADIO:
                    p.listarRadios();
                    break;
            }
        }
    }
}

Si queda alguna duda solo escribe
;-)
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar
sin imagen de perfil
Val: 6
Ha aumentado su posición en 2 puestos en Java (en relación al último mes)
Gráfica de Java

Java. Ayuda con este ejercicio

Publicado por Alfonso (4 intervenciones) el 19/01/2019 01:02:54
Muchísimas gracias por la respuesta.

Probé el programa y funciona como es debido.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar