-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTryCatchFinally.java
More file actions
48 lines (43 loc) · 1.43 KB
/
Copy pathTryCatchFinally.java
File metadata and controls
48 lines (43 loc) · 1.43 KB
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
/**
* Ejercicio de prueba usando try-catch-finally con manejo de excepciones.
*
* Se pide repetidamente al usuario un número entre 0 y 100, mediante un bucle
* do-while.
*
* Se utiliza el método readLine() de la clase BufferedReader porque puede
* lanzar la excepción IOException. Si no se hace nada con ella cuando se
* produce, el programa finaliza.
*
* Así mismo, el método parseInt() puede lanzar la excepción
* NumberFormatException, cuando parseInt() no puede convertir el texto en un
* número entero.
*
* Apunte: el bloque finally siempre se ejecuta.
*/
import java.io.*;
public class TryCatchFinally {
public static void main(String[] args) {
int numero = 0;
int intentos = 0;
String linea;
BufferedReader teclado = new BufferedReader(new InputStreamReader(System.in));
do {
try {
System.out.print("Introduzca un número entre 0 y 100: ");
linea = teclado.readLine();
numero = Integer.parseInt(linea);
}
catch(IOException e) {
System.out.println("Error al leer del teclado!");
}
catch(NumberFormatException e) {
System.out.println("Numero a introducir entre 0 y 100!");
}
finally {
intentos++;
}
} while (numero < 0 || numero > 100);
System.out.println("El numero introducido es: " + numero);
System.out.println("Total de intentos: " + intentos);
}
}