jQuery in Action, 2nd edition*
The moose likes Java in General and the fly likes How to validate a Scanner keyboard input? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to validate a Scanner keyboard input?" Watch "How to validate a Scanner keyboard input?" New topic
Author

How to validate a Scanner keyboard input?

Enrique Villamizar
Ranch Hand

Joined: Jul 30, 2005
Posts: 93
I�m trying to use the Scanner class. The idea is to design a class for getting primitive values from the user but I need to be sure that user�s inputs are valid primitive values.
I read the java docs and here is what I found:
�When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.� JavaTM 2 Platform Standard Ed. 5.0

So, I create the following class: (Spanish is my mother tongue)

import java.io.*;
import java.util.Scanner;
import java.util.InputMismatchException;

public class Leer{

private static Scanner s = new Scanner(System.in);
private static int numeroEntero;
public static int entero(){

try{
numeroEntero = s.nextInt();
}//close try block
catch(InputMismatchException e){
System.out.println("ERROR: ERROR: An integer required");
return entero();
}//close catch() block
s.close(); /* Cierra la entrada */
return numeroEntero;
}//close entero() method
}//close Leer class

BUT WHEN I RUN

class LeerTest{

public static void main(String[]args){
System.out.print("Input an integer: ");
System.out.println(Leer.entero());

}//close main()
}//close LeerTest

IF AN INVALID DATA INPUT THE PROGRAM EXECUTES AN INFINITIVE LOOP. I USED THE SAME IDEA WITHOUT USING SCANNER AND NO PROBLEM. Please look the following:
import java.io.*;

public class Leer {
public static String capturaDatos() {
String datoString = "";
try {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader teclado = new BufferedReader(isr);
datoString = teclado.readLine();
}//cerramos try
catch(IOException e) {
System.out.println("Ocurri� un error: " + e.getMessage());
} //cerramos catch
return datoString;
} //cerramos capturaDatos()
public static int datoInt() {
try {
return Integer.parseInt(capturaDatos());
}
catch(NumberFormatException e) {
System.out.println("Error: Digite un entero maximo hasta 2147483647");
return datoInt();
}
} //cerramos datoInt()
}//cierra Leer
[ October 02, 2005: Message edited by: Enrique Villamizar ]
Kenneth Albertson
Ranch Hand

Joined: Sep 18, 2005
Posts: 59
You have already answered your own question, Enrique:
Originally posted by Enrique Villamizar:I read the java docs and here is what I found:
�When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.� JavaTM 2 Platform Standard Ed. 5.0
Invalid inputs cause your code to enter an infinite loop because it just keeps retrying the same input. It needs to discard it. This will do the trick:A few other comments:
  • The input prompt comes from the driver, perhaps the error message, decision to retry, and prompt for re-enty, should come from there too?
  • You could avoid the exception altogether by using Scanner.hasNextInt()

  • Enrique Villamizar
    Ranch Hand

    Joined: Jul 30, 2005
    Posts: 93
    Thanks Kym for your help. You�re right. Scanner.nextLine() did its job. To be honest I don�t know how to avoid the exception by using Scanner.hasNextInt() since its returns a boolean. I have another question: what could be happen if I don�t close the Scanner?

    Once again thank you. When I get enough knowledge to help others I�ll do it! (Maybe some day!)
    Julien Grenier
    Ranch Hand

    Joined: Sep 01, 2005
    Posts: 41

    o be honest I don�t know how to avoid the exception by using Scanner.hasNextInt() since its returns a boolean.


    something like that


    There's probaby better ways but that's one of them
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: How to validate a Scanner keyboard input?
     
    Similar Threads
    how to link a keyboard to the program...
    Program example using KeyboardReader
    i guess using variables from one class into another class all in the same package?
    input from console