Check Valid Number In Java String

Some times we need to check whether user input a valid number or not. If not, we need to tell user to input a valid number again. In this example, we will show you two method about how to verify a valid number value in a Java String variable.

Use Double.parseDouble() and Integer.parseInt()

	/* Use Double and Integer parse method to check. */
	private static boolean ifValidNumber(String str)
	{
		boolean ret = true;
		try
		{
			if(str!=null)
			{
				str = str.trim();
				int dotIndex = str.indexOf(".");
				
				/* If contain dot, then it should be a double number.*/
				if(dotIndex>-1)
				{
					Double.parseDouble(str);
				}else
				{
					/*If not contain dot, then it should be a integer String. */
					Integer.parseInt(str);
				}
			}
		}catch(NumberFormatException ex)
		{
			/* If parse String method throw a NumberFormatException, then it is not a String. */
			ex.printStackTrace();
			ret = false;
		}
		
		return ret;
	}

Use Apache Commons Lang StringUtils

  1. Go to Apache Commons Lang Project Home Page.
  2. Click Download link in left panel.
    apache commons lang home page
  3. Download the latest stable version Apache Commons Lang3.6 in download page.
    apache commons lang download page
  4. Extract the download zip file into a local folder, such as C:/WorkSpace/dev2qa.com/Lib.
  5. Add the commons-lang3-3.6.jar file into your java project’s build path. Right click the java project, click ” Build Path —> Configure Build Path “.
    configure java build path in java project
  6. Click ” Add External JARS ” button in popup dialog.
    add selenium webdriver server standalone jar file in java project properties
  7. Browse to the extracted zip file folder, select commons-lang3-3.6.jar. Click OK to add it.
  8. Now you can use below java code to implement this function.
    	/* Use Apache Commons Lang project StringUtils to check. */
    	private static boolean ifValidNumberByApacheCommonsLang(String strNum)
    	{
    		boolean ret = StringUtils.isNumeric(strNum);
    		return ret;
    	}

Java Main Method

	public static void main(String[] args) {
		
		String strArr[] = {"123", "12.3", "123df56", "abcde", "[email protected]"};
		
		for(String strNum : strArr)
		{
			//boolean isValidNumber = CheckValidNumberInJavaString.ifValidNumber(strNum);
			
			boolean isValidNumber = CheckValidNumberInJavaString.ifValidNumberByApacheCommonsLang(strNum);
			
			if(isValidNumber)
			{
				System.out.println(strNum + " is a valid number");
			}else
			{
				System.out.println(strNum + " is not a valid number");
			}
		}

	}

Download “CheckValidNumberInJavaString.zip” CheckValidNumberInJavaString.zip – Downloaded 60 times – 828 B

(Visited 239 times, 1 visits today)
READ :   How To Integrate JUnit Framework Into Selenium Scripts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.