Win a copy of Murach's MySQL this week in the JDBC and Relational Databases forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to validate a Scanner keyboard input?

 
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
    Posts: 93
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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!)
     
    Ranch Hand
    Posts: 41
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator


    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
     
    reply
      Bookmark Topic Watch Topic
    • New Topic