Foro de elhacker.net

Programación => Java => Mensaje iniciado por: nico56 en 8 Julio 2010, 21:23 pm



Título: Ayuda con esta funcion
Publicado por: nico56 en 8 Julio 2010, 21:23 pm
Hola que tal, estoy haciendo una funcion para pedir un numero entero, quiero que si el usuario lo inserta mal que lo vuelva a pedir, para ello hice esta funcion:

Código
  1. public static int pedir_entero(String s)
  2. {
  3. int aux = 0;
  4. boolean correct=false;
  5. Scanner stdin=new Scanner(System.in);
  6.  
  7. while(correct == false)
  8. {
  9. try
  10. {
  11. System.out.print(s);
  12. aux=stdin.nextInt();
  13. stdin.next();
  14. correct=true;
  15.    }
  16. catch(InputMismatchException e)
  17. {
  18. System.out.println("ERROR," + s);
  19. }
  20. }
  21.  
  22. return aux;
  23. }
  24.  

Cuando la pruebo poniendo una letra, se cuelga el programa mostrandos repetitivamente e infinitamente esta sentencia:

"System.out.println("ERROR," + s);"

Que puede ser? Desde ya gracias y saludos.


Título: Re: Ayuda con esta funcion
Publicado por: Debci en 8 Julio 2010, 21:55 pm
Mira fijate que mete el catch dentro del while, por eso cuando hay un error lanzas la captura de exepcion indefinidamente, para que no ocurra, deberia ser algo asi:

Código
  1. public static int pedir_entero(String s)
  2. {
  3. int aux = 0;
  4. boolean correct=false;
  5. Scanner stdin=new Scanner(System.in);
  6.  
  7.                     try{
  8. while(correct == false)
  9. {
  10.  
  11. System.out.print(s);
  12. aux=stdin.nextInt();
  13. stdin.next();
  14. correct=true;
  15.    }
  16.  
  17. }
  18.                 catch(InputMismatchException e)
  19. {
  20. System.err.println("Error!");
  21. }
  22. return aux;
  23. }

Como puedes ver he metido el catch fuera, no he probado el codigo, pues lo hice rapido aqui mismo, si no va dimelo y te lo pruebo, pero en principio no ha de haber problemas.

Saludos


Título: Re: Ayuda con esta funcion
Publicado por: Serghinio12 en 8 Julio 2010, 22:11 pm
Hola a to@s, llevo un tiempo registrado aunque no suelo postear.
He modificado un poco tu codigo pero creo que funciona:

Código:
public static int pedir_entero(String s) {
        int aux = 0;
        boolean correct = false;
        Scanner stdin = new Scanner(System.in);
        while (correct == false) {
            try {
                System.out.print(s);
                aux = stdin.nextInt();
                correct = true;
            } catch (InputMismatchException e) {
                System.out.println("ERROR," + s);
                stdin.next();
            }
        }

        return aux;
    }

Y debci me parece que tu codigo no te lo vuelve a pedir si es erroneo.


Título: Re: Ayuda con esta funcion
Publicado por: Debci en 8 Julio 2010, 22:20 pm
Hola a to@s, llevo un tiempo registrado aunque no suelo postear.
He modificado un poco tu codigo pero creo que funciona:

Código:
public static int pedir_entero(String s) {
        int aux = 0;
        boolean correct = false;
        Scanner stdin = new Scanner(System.in);
        while (correct == false) {
            try {
                System.out.print(s);
                aux = stdin.nextInt();
                correct = true;
            } catch (InputMismatchException e) {
                System.out.println("ERROR," + s);
                stdin.next();
            }
        }

        return aux;
    }

Y debci me parece que tu codigo no te lo vuelve a pedir si es erroneo.
Claro que no, el no ha pedido tal caracteristica, por cierto poned las tags de codigo en java con:
Código:
[code=java]

Saludos[/code]


Título: Re: Ayuda con esta funcion
Publicado por: nico56 en 8 Julio 2010, 23:39 pm
Si me habia equivocado, la idea era volver a pedirlo si lo insertaba mal.


Título: Re: Ayuda con esta funcion
Publicado por: Leyer en 9 Julio 2010, 00:02 am
Código
  1. public static int pedir_entero()
  2. {
  3. int aux = 0;
  4. Scanner stdin=new Scanner(System.in);
  5. try{
  6. System.out.println("N: ");
  7. aux=Integer.parseInt(stdin.next());
  8. }catch (Exception e) {
  9. System.err.println(e.getMessage());
  10. pedir_entero();
  11. }
  12. return aux;
  13. }
  14.  

Código
  1. public static int pedir_entero1()
  2. {
  3. int aux = 0;
  4. Scanner stdin=new Scanner(System.in);
  5. do{
  6. try{
  7. System.out.println("N: ");
  8. aux=Integer.parseInt(stdin.next());
  9. break;
  10. }catch (Exception e) {
  11. System.err.println(e.getMessage());
  12. continue;
  13. }
  14. }while(true);
  15. return aux;
  16. }


Título: Re: Ayuda con esta funcion
Publicado por: 43H4FH44H45H4CH49H56H45H en 9 Julio 2010, 04:38 am
Código
  1. package entero;
  2. import java.util.Scanner;
  3. public class Main {
  4.    public static void main(String[] args) {
  5.        String res="";
  6.        do
  7.        {
  8.            Scanner leer=new Scanner(System.in);
  9.            res = leer.next();
  10.        }while(!esNumero(res));
  11.  
  12.        Integer resul = Integer.parseInt(res)+ 24;
  13.        System.out.println("Numero: " + res + " sumado + 24 = " + resul);
  14.    }
  15.    public static boolean esNumero(String valor)
  16.    {
  17.        try
  18.        {
  19.            Integer.parseInt(valor);
  20.            return true;
  21.        }
  22.        catch(NumberFormatException error)
  23.        {
  24.            System.out.println("No es numero, error: " + error);
  25.            return false;
  26.        }
  27.    }
  28. }
  29.  


Título: Re: Ayuda con esta funcion
Publicado por: joseprox en 13 Julio 2010, 01:35 am
Prueba CON ESTE......

Código
  1. import java.io.*;
  2.  
  3. public class Pedirnumero implements Serializable{
  4.  
  5. public static void main(String a[]){
  6.  
  7. String dato = "";
  8.  
  9. try{
  10.  do{
  11.  
  12. System.out.print("Digite numero: "); dato = rs.readLine();
  13.  
  14.  
  15.  }while(pedirnumero(dato));
  16.  
  17.  System.out.println("DATO CORRECTO : "+dato);
  18.  
  19.  
  20. }catch(Exception e){
  21.  
  22.  System.out.println("Error en "+e.getMessage());
  23.  
  24.  }
  25. }//fin main
  26.  
  27.  
  28. public static boolean pedirnumero(String dato){
  29.  
  30. try{
  31.  
  32.     Integer.parseInt(dato);
  33.  
  34.     return false;
  35.  
  36. }catch(Exception e){
  37.     System.out.println("Dato no permitido: "+dato);    
  38.     return true;
  39. }
  40.  
  41. }
  42.  
  43. }

Leyer: Utilizar las quotes de codigo java de GeShi para la proxima