Thursday, November 11, 2010

Java-Simple way to check command line input to enter a number-Give error message if not a number and ask again to input

If you want to take a commandline input through BufferedReader or Scanner and you want user to enter a number. So in this solution user is asked to enter a number and if it is not a number (throws NumberFormatException) error message is displayed and again asks for user to enter. Until user enters a number this continues. This is simple.

Here is the code with comments explaining the code.

import java.io.*;
class InputNumber{
 public static void main(String args[]){
  boolean success=false;
  String value=null;
  int number_value=0;//number value is stored
  System.out.print("Enter Number:");
              
              //loop continues until user entered a number,success 
              //will assigned true when user entered a number and while
              //loop will terminate
              while (!success){
   try{
      BufferedReader bf=new BufferedReader
         (new InputStreamReader(System.in));
      value=bf.readLine();
      number_value=Integer.parseInt(value);


           success=true;//Come to this point only if the 
                                    // exception is not thrown
     System.out.println("\nSuccess! You Entered a Number: "+number_value);

   }catch(IOException e){


   }catch(NumberFormatException e){//When string did 
                                      //not contained a numer it goes here
    System.out.print("\nWrong value, please enter a number!\nEnter Number :");
    success=false;

   }
  }
 }


}

1 comment:

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete