Java code to check given String is Numeric or not example

This tutorial shows you how to check given string is numeric or not using java code. Suppose you need to calculate the sum of 3 marks (integer only). For calculating sum of the 3 marks , you may need to accept 3 marks as input through console. Java accepts marks as a string, so these string numbers has to be converted to integer before calculation. Before that we may check that the input strings contains only digits ( i.e. the input string is Numeric or not ). This can be done in many ways. Let us do in two ways. In first method we have written own function isNumeric() to check each characters is digit or not using Charater.isDigit(). In the Second method, using NumberFormatException by putting the Integer.parseInt(str) in a try..catch block. if the input mark is not a valid numeric means it will throw error. The java code to check the given string is numeric or not is given below

package net.javaonline;

import java.io.*;

class NumericValidation

{

	public static void main(String args[])

	{

		String mark1 = "", mark2 = "", mark3 = "";

		int sum = 0, sum1 = 0;

		System.out.println("3 Marks one by one ");

		try

		{

			BufferedReader br = new BufferedReader(new InputStreamReader(
					System.in));

			mark1 = br.readLine();

			mark2 = br.readLine();

			mark3 = br.readLine();

		} catch (Exception e)

		{

			System.out.println("Error");

		}

		sum = sumMethod1(mark1, mark2, mark3);

		System.out.println("Sum of Marks using Method 1   :" + sum);

		sum1 = sumMethod2(mark1, mark2, mark3);

		System.out.println("Sum of Marks using Method 2    :" + sum1);

	}

	private static int sumMethod1(String mark1, String mark2, String mark3)

	{

		System.out.println("Inside sumMethod1");

		int sum = 0;

		if (isNumeric(mark1) && isNumeric(mark2) && isNumeric(mark3))

		{

			sum = Integer.parseInt(mark1) + Integer.parseInt(mark2)
					+ Integer.parseInt(mark3);

		}

		else

		{

			System.out
					.println("InNot a Valid Marks. Please enter only integer ");

		}

		return sum;

	}

	// Function to check that a string contains only digits

	public static boolean isNumeric(String markStr)

	{

		int strLength = markStr.trim().length();

		for (int i = 0; i < strLength; i++)

			if (!Character.isDigit(markStr.charAt(i)))
				return false;

		return true;

	}

	private static int sumMethod2(String mark1, String mark2, String mark3)

	{

		System.out.println("Inside sumMethod2");

		int sum = 0;

		try

		{

			sum = Integer.parseInt(mark1) + Integer.parseInt(mark2)
					+ Integer.parseInt(mark3);

		}

		catch (NumberFormatException e)

		{

			System.out
					.println("Not a Valid Marks. Please try with only integer ");

		}

		return sum;

	}

}

Output of the above program ::

numeric validation numeric validation1

 

 

Leave a Reply