Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Code Experiment on Integer Validation

, 3 Dec 2013
Rate this:
Please Sign up or sign in to vote.
Explore the different integer validation methods.

Introduction

Recently, I came across a question asking about integer validation in Java. The question asked that a user of a program to be prompted to enter an integer value for each time that he fails to do so. While solving the question, I noticed certain malpractice that led to misuse of programming method. I have decided to do some research followed by conducting code experiments on three methods of integer validation using Java. This article describes these methods and discusses their pros and cons. Although the experiments were done in Java program for integer validation, the idea is equally applicable to other programming languages and other data type validation.

Using the Code

The three demo programs that come with this article are console applications written in Java. Once launched, these three programs, though written differently, will appear and behave identically on the console screen. Follow the steps below to set them up for test run on your computer.

  1. First of all, you have to have a Java SE Development Kit (JDK) installed on your computer, if not just download the latest version from the Oracle website.
  2. Download and unzip the source files - ValidateIntegerWithTryCatch.java, ValidateIntegerWithoutTryCatch.java, and ValidateIntegerWithRegex.java, and move them to a location say c:\.
  3. Open a terminal screen (Command Prompt in Windows), navigate to the directory where the Java programs reside, type javac ValidateIntegerWithRegex.java to compile and you should get a class file named ValidateIntegerWithRegex.class. Do likewise for the remaining two programs.
  4. Now, you can launch the program by simply typing java com.peterleow.ValidateIntegerWithRegex on the terminal screen. Do likewise for the remaining two programs.

If you encounter problems with these instructions, consult the Common Problems (and Their Solutions), courtesy of Oracle.

The Experiments

The Evil - Try and Catch Method

The try and catch approach seems to be the commonest choice for implementing integer validation when I Google on this topic. I supposed that is because this method is the easiest to learn and implement. The first program below shows an example of an integer validation using the try and catch method.

/*
*   Integer Validation with Try Catch
*/

package com.peterleow;
 
import java.util.Scanner;
 
public class ValidateIntegerWithTryCatch {
 
    public static void main(String[] args) {
 
        Scanner sc=new Scanner(System.in);
        int number = 0;
        boolean isMismatched;
        do {
            isMismatched = false;
            try
            {
                System.out.print("Please input an integer ");
 
                String usrInput=sc.next();
 
                number = Integer.parseInt(usrInput);
 
            }
            catch(NumberFormatException ex)
            {
                isMismatched = true;
            }
        } while (isMismatched);
 
        System.out.println("Validation Pass!");
        System.out.println("You have entered " + number);
        sc.close();
    }
}

I must say that using the try and catch method to validate inputs is a malpractice and should not be perpetuated. The reason being that Exception handling is supposed to be used for exception handling only. Exception handling will impose overhead in terms of execution time when an exception occurs. In this program, it is being wrongly used to control the flow.

The Faithful - Flow Charting Method

I coin this second method the flow charting method because it mirrors the flow chart way of problem solving as shown in this second program below.

/*
*   Integer Validation without Try Catch
*/

package com.peterleow;

import java.util.Scanner;

public class ValidateIntegerWithoutTryCatch {

    public static void main(String[] args) {
        
        Scanner sc=new Scanner(System.in);

        int number = 0;
        boolean isNegative;
        boolean isMismatched;
        
        String str;
  
        do{
            isNegative = false;
            isMismatched = false;
     
                System.out.print("Please input an integer ");
 
                String userInput = sc.next().trim();
               
                StringBuilder sb = new StringBuilder(userInput);
         
                // remove negative sign if any
                if (sb.substring(0, 1).equals("-")){
                    isNegative = true;
                    sb.deleteCharAt(0);
                } 
          
                str = sb.toString();
                char c;
                for(int i = 0; i < sb.length(); i++){
                    
                    c = sb.charAt(i);
                    
                    if (!Character.isDigit(c)){
                        // fail integer validation
                        isMismatched = true;
                        break;
                    } 
                }

        } while (isMismatched);
 
        // pass integer validation
        number = Integer.parseInt(str, 10);;
        
        // restore negative sign if any
        if (isNegative){
            number = -number;
        }
 
        System.out.println("Validation Pass!");
        System.out.println("You have entered " + number);
        sc.close();
    }
}

There is nothing wrong with this method except that it is long-winded and tedious to program. For teaching programming fundamentals, this makes for a good programming exercise. But for the veterans, there is a better way.

The Match Maker - Regular Expression

We have finally arrived at the regular expression. In programming, a regular expression, regex in short, defines a search pattern of strings. Regex is an efficient and powerful tool that is widely used for searching and matching text pattern. Its use is extended beyond data validation to other fields of study such as text mining and information retrieval. Programs that use regex are usually shorter and cleaner than the other methods. The program below uses regex to do integer validation.

/*
*   Integer Validation with Regex
*/

package com.peterleow;

import java.util.Scanner;

public class ValidateIntegerWithRegex {

    public static void main(String[] args) {
           
        Scanner sc=new Scanner(System.in);
        String usrInput;
        boolean isMismatched;
            
        // regex for zero or one '-' and followed by one or more digits
        String regex = "\\-?\\d+";
            
        do {
                System.out.print("Please input an integer ");
     
                usrInput = sc.next();
   
                isMismatched = !usrInput.matches(regex);

        } while (isMismatched);
 
        System.out.println("Validation Pass!");
        System.out.println("You have entered " + Integer.parseInt(usrInput));
        sc.close();
    }
}

However, the drawback is that the learning curve is much steeper. But, the payoff is worth the effort. You can have a good head start at Java Regex Tutorial.

The Verdict

We have explored the three methods of integer validation and experimented with the demo programs. My verdict is regex. What is yours?

History

  • First edition: 01 Dec 2013. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Peter Leow
Instructor / Trainer
Singapore Singapore
Graduated from the National University of Singapore with the following qualifications:
1. Graduate Diploma in Systems Analysis (2002)
2. Master of Technology (Knowledge Engineering) (2013)
 
Currently, lecturing in the area of social media and web development at a technical institution.
 
Having hibernated for ages, finally woke up to serve the Community in Oct 2013.
Follow on   LinkedIn

Comments and Discussions

 
GeneralGood Explanation. I got some information from this. PinmemberVijaydhas6-Dec-13 3:54 
GeneralRe: Good Explanation. I got some information from this. PinprofessionalPeter Leow6-Dec-13 4:01 
GeneralI don't completely agree with this PinmemberJohn Brett2-Dec-13 23:21 
GeneralRe: I don't completely agree with this [modified] PinprofessionalPeter Leow3-Dec-13 0:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140922.1 | Last Updated 3 Dec 2013
Article Copyright 2013 by Peter Leow
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid