Pages

Java validate integer user input


Sometime, when we play with user input, we want to validate the input value is specific to certain data type. For example, you have a simple java program that query for user's age. Like we know age is in integer data type. So how to handle if a user put his age something like this, "fifty" or 50.34. This is impossible right? But if the user want to test the robustness of your system from error handling view, this is not impossible.Now i want to share with you, how you can handle this in a simple java program that run through command prompt.The basic idea is, if a user put other than integer value, our program will throw an exception. So, we will put our code that tell user what he/she do is wrong in the exception block.In other tutorial, i will share with you how to create your own exception handling.

***************************************************************
COMPLETE SOURCE CODE FOR : ValidateIntegerInput.java
***************************************************************


import java.util.Scanner;
import java.util.InputMismatchException;

public class ValidateIntegerInput
{
public static void main(String[]args)
{
boolean benchmark=true;
while(benchmark)
{
Scanner a=new Scanner(System.in);

try
{
System.out.println("Put 0 to exit");
System.out.println("What is your age?");

//nextInt will throw InputMismatchException
//if the next token does not match the Integer
//regular expression, or is out of range
int b=a.nextInt();
if(b==0)
{
benchmark=false;
}
else
{
System.out.println("Your age is : "+b);
}
}
catch(InputMismatchException exception)
{
//Print "This is not an integer"
//when user put other than integer
System.out.println("Please put integer value");
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}
}


***************************************************************
JUST COMPILE AND EXECUTE IT
***************************************************************
Related Posts Plugin for WordPress, Blogger...

I Also Can Create T-Shirt Logo For You