package com.mindprod.example;
import com.mindprod.common18.ST;
import static java.lang.System.*;
/**
* Demonstrate various ways of implementing isNumeric.
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2012-03-14 initial version
* @since 2012-03-14
*/
@SuppressWarnings( { "UnusedAssignment" } )
public final class TestIsNumeric
{
/**
* Test if a string is any legitimate double format including exponent, not localised.
*
* @param s String to test
*
* @return true if valid double
*/
private static boolean isDouble( String s )
{
try
{
Double.parseDouble( s );
}
catch ( NumberFormatException e )
{
return false;
}
return true;
}
/**
* test if a string is numeric. Allow embedded spaces, + and -.
*
* @param s String to test
*
* @return true if numeric
*/
private static boolean isRelaxedNumeric( String s )
{
return ST.isLegal( s, "0123456789+- " );
}
/**
* test if a string is numeric. Integer only. Allows lead minus sign. no commas or decimal points
*
* @param s String to test
*
* @return true if numeric
*/
private static boolean isSignedInteger( String s )
{
try
{
Integer.parseInt( s );
}
catch ( NumberFormatException e )
{
return false;
}
return true;
}
/**
* test if a string is numeric. Only digits allowed, including foreign language digits.
*
* @param s String to test
*
* @return true if numeric
*/
private static boolean isUnsignedInternationalNumeric( String s )
{
for ( int i = 0; i < s.length(); i++ )
{
if ( !Character.isDigit( s.charAt( i ) ) )
{
return false;
}
}
return true;
}
/**
* test if a string is numeric. Integer only. No lead - allowed.
* This method is also available as com.mindprod.common18.ST.isUnsignedNumeric
*
* @param s String to test
*
* @return true if numeric
*/
private static boolean isUnsignedNumeric( String s )
{
for ( int i = 0; i < s.length(); i++ )
{
char c = s.charAt( i );
if ( c < '0' || c > '9' )
{
return false;
}
}
return true;
}
/**
* Test ways of testing if numeric.
*
* @param args not used
*/
public static void main( String[] args )
{
out.println( isDouble( "-1234.00E21" ) );
out.println( isDouble( "-1,223.4E21" ) );
out.println( isRelaxedNumeric( "1 2+34" ) );
out.println( isRelaxedNumeric( "-122.34" ) );
out.println( isSignedInteger( "-1234" ) );
out.println( isSignedInteger( "-1,223.4" ) );
out.println( isUnsignedInternationalNumeric( "1123\u096c" ) );
out.println( isUnsignedInternationalNumeric( "-12234" ) );
out.println( isUnsignedNumeric( "1234" ) );
out.println( isUnsignedNumeric( "-12234" ) );
}
}