Re: IsNumber function
Mark Space wrote:
Salad wrote:
I'm just beginning. I didn't find a IsNumeric() or IsNumber() method
so I wrote my own. The method can take a string, number or boolean
and determine if it's a number or not (I didn't check for chars).
Could you take a look at it and tell me what I can change that makes
it easier to use? I would prefer if I could use a format like
boolean b = IsNumber("123");
b = IsNumber("Mary");
b = IsNumber("123.0")
Yes, just use static methods:
////////////// Start Code
package local;
public class NumberUtils
{
private NumberUtils() { }
public static boolean isNumber( String num )
{
try {
Double.parseDouble( num );
return true;
}
catch( Exception e ) {
return false;
}
}
public static boolean isNumber( double d ) {
return true;
}
public static boolean isNumber( boolean b ) {
return false;
}
}
/////////// END CODE
Then test/use like this:
///////////START CODE
package fubar;
import static local.NumberUtils.*;
public class TestIsNumber
{
//test the method
public static void main( String args[] )
{
//string alpha
String strVar = "Mary";
System.out.println( "The value is " + isNumber( strVar ) );
//string numeric
strVar = "123";
System.out.println( "The value is " + isNumber( strVar ) );
//int
int intVar = 123;
System.out.println( "The value is " + isNumber( intVar ) );
//double
double dblVar = 123.00;
System.out.println( "The value is " + isNumber( dblVar ) );
//boolean
boolean boolVar = true;
System.out.println( "The value is " + isNumber( boolVar ) );
}
}
// END CODE
Very cool. Use overload on the methods and call it.
You might also want to take a look at this (note the section where they
talk about checking a number format with out throwing an exception; they
use Regex. Also note that NumberFormat can check for number formats in
different locales.):
<http://java.sun.com/javase/6/docs/api/java/lang/Double.html#valueOf(java.lang.String)>
Finally, I realize that you are just starting, BUT: there's no reason in
a statically typed language to check if booleans or ints are numbers.
Booleans never are, and ints always are. Ditto for the rest of your
"IsNumber" methods, except the String one.
I'm coming from VB. I was in a VB debug window and entered
? IsNumeric(123)
True
? IsNumeric("Mary")
False
? IsNumeric(True)
True
so I thought I'd try it out in Java. See if I could do it.
Sidenote: In VB, True is -1, False is 0. But they're considered
numbers. Ex:
? 1 + true
0
? 2 + true
1
? 1 + false
1
I know what you are saying but some functions I've written in the past
I've never cared what type of data gets passed to it in a VBA function
(method) and have used a variant...which basically is what you did there
with the overloading.
My code used constructors, yours didn't. I need to learn when to use
constructors and when not to.