Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

IsNumber function

177 views
Skip to first unread message

Salad

unread,
Apr 10, 2009, 7:23:00 PM4/10/09
to
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")

public class IsNumberTest
//test the method
{
public static void main(String args[])
{

//string alpha
String strVar = "Mary";
IsNumber test = new IsNumber(strVar);
System.out.println("The value is " + test.getNumber());

//string numeric
strVar = "123";
test = new IsNumber(strVar);
System.out.println("The value is " + test.getNumber());

//int
int intVar = 123;
test = new IsNumber(intVar);
System.out.println("The value is " + test.getNumber());

//double
double dblVar = 123.00;
test = new IsNumber(dblVar);
System.out.println("The value is " + test.getNumber());

//boolean
boolean boolVar = true;
test = new IsNumber(boolVar);
System.out.println("The value is " + test.getNumber());
}
}


//checks if the value passed is a number or not
public class IsNumber
{
private boolean returnval;

//start constructiors
public IsNumber(float passed)
{
isNumber(true);
}

public IsNumber(double passed)
{
isNumber(true);
}

public IsNumber(long passed)
{
isNumber(true);
}

public IsNumber(int passed)
{
isNumber(true);
}

public IsNumber(short passed)
{
isNumber(true);
}

public IsNumber(byte passed)
{
isNumber(true);
}

public IsNumber(boolean passed)
{
isNumber(false);
}

public IsNumber(String passed)
{
try
{
Double.parseDouble( passed );
isNumber(true);
}
catch( Exception e )
{
isNumber(false);
}
}
//end constructors


public void isNumber(boolean tf)
{
returnval = tf;
}

public boolean getNumber()
{
return returnval;
}

}

Mark Space

unread,
Apr 10, 2009, 7:59:46 PM4/10/09
to
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


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.

Salad

unread,
Apr 11, 2009, 1:06:29 AM4/11/09
to
Mark Space wrote:

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.

RedGrittyBrick

unread,
Apr 11, 2009, 6:54:26 AM4/11/09
to
Salad wrote:
>
> 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.
>

In the past, when learning language B after language A, I have found it
a great mistake to try *too* hard to apply what I know of A to B.
Nowadays I try to pick up the new language's idioms as fast as possible
and avoid writing in B using A's idioms. That way leads to confusion and
pain IME. I find it can slow down learning and create bad habits.

YMMV.

--
RGB

Andre Weihe

unread,
Apr 11, 2009, 8:11:29 AM4/11/09
to
Mark Space wrote:

> public static boolean isNumber( double d ) {
> return true;
> }

A double can be "Not a number" when its value is Not-a-number (NaN).

So I would rewrite this to:
public static boolean isNumber(double d) {
return !(Double.isNaN(d));
}
--
I'm a single and would like to be a double or at least a float.

Patricia Shanahan

unread,
Apr 11, 2009, 9:38:00 AM4/11/09
to
Salad wrote:
...

> 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.
...

Learning any language X in terms of a known language Y is dangerous. The
risk is that you will try to translate language Y idioms to language X,
instead of achieving fluency in language X idioms. The result will be
awkward X code that others will find hard to read, and a feeling that
you are fighting the language.

Here, you are borrowing a problem and its solution from VB. The question
your method is trying to answer does not make sense in Java.

If a method requires e.g. a double, it will be specified to take a
double argument. On the other hand, if you have a String and need to
parse it as a double, the normal approach would be to do the conversion.
If it fails, catch the exception and do something appropriate.

I think you might be better off forgetting VB for a while and learning
to write idiomatic Java.

Patricia

Message has been deleted
Message has been deleted
Message has been deleted
Message has been deleted

Mark Space

unread,
Apr 11, 2009, 11:52:50 AM4/11/09
to
Salad wrote:

> 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.


Stefan had some interesting code. He didn't use method overloading but
instead auto-boxing. Primitives (ints, bytes, booleans, etc) can be
boxed into Objects (Integers, Bytes, Booleans, etc) and then used in the
type system. The disadvantage of this is that creating these Objects
takes system resources and is slower than just passing a primitive directly.

What I did is not overloading, so much. I declared one method that took
a double and used *widening* to pass all the numeric types to it. The
primitive double is the widest type of number in Java, so all numbers
can be passed to that method. Then I added one overloaded method to
catch the booleans, and I was done. The disadvantage of this is that
widening also takes system resources and in my opinion is poor practice,
since it creates code that can be hard to read or debug. Methods that
take a specific type are preferred.

The bigger issue is, as mentioned by myself and now three other folks on
this thread, is that you should never need to test an object that you
thought you didn't care about for its type. You can overload methods
just the way I did, avoid auto-boxing, avoid the run time overhead of
testing for a type, and always just know what type you have.

Stefan's code also used widening (from auto-boxed primitives up to
Object) and you see that folks are complaining about it. Widening
should not be used unless the type you really want is in fact Object.
And in that case, you should only use Object's methods, you shouldn't
need to be testing for other types.

>
> My code used constructors, yours didn't. I need to learn when to use
> constructors and when not to.


I also added a trick where I declared the default constructor private,
thus preventing the user from accidentally calling a constructor that
did nothing. It's a documentation and user-friendly-API thing.
Something to be on the look-out for as you write your own code.


> I'm coming from VB. I was in a VB debug window and entered
> ? IsNumeric(123)
> True
> ? IsNumeric("Mary")
> False


My Java debugger has a GUI, where the type of each variable is displayed
right next to the name, so I never have to wonder, it's right there in
front of me. Maybe you should try a better debugger. Just sayin'....

Eric Sosman

unread,
Apr 11, 2009, 1:22:23 PM4/11/09
to
Patricia Shanahan wrote:
> Salad wrote:
> ...
>> 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.
> ...
>
> Learning any language X in terms of a known language Y is dangerous. The
> risk is that you will try to translate language Y idioms to language X,
> instead of achieving fluency in language X idioms. The result will be
> awkward X code that others will find hard to read, and a feeling that
> you are fighting the language.

As was observed long ago, a Real Programmer is someone
who can write FORTRAN in any language.

--
Eric Sosman
eso...@ieee-dot-org.invalid

Lew

unread,
Apr 11, 2009, 5:15:30 PM4/11/09
to
Salad wrote:
> My code used constructors, yours didn't. I need to learn when to use
> constructors and when not to.

Think of constructors as things that construct objects, and methods as things
that fully-constructed objects use to get things done.

Don't use an incompletely-built object to get things done.

That leads one to avoid overridable methods from inside a constructor. It
leads one not to create too many side effects from a constructor.

You do some work in constructors, but it usually isn't public work. It's work
on behalf of the fetal object under construction.

Once the instance is complete, it can announce itself to the world and start
working for its living. That work is done via methods, not constructors.

You can transcend these rules somewhat once you've mastered them, but that's
inadvisable until then.

--
Lew

Salad

unread,
Apr 12, 2009, 9:17:07 PM4/12/09
to
Mark Space wrote:

Thanks to all that contributed to this thread. I'd respond to each
person's response but I hope all of them know I found their replies
enlightening.

0 new messages