IsNumber function

IsNumber function

Post by Sala » Sun, 12 Apr 2009 08:23:00


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;
}

}
 
 
 

IsNumber function

Post by Mark Spac » Sun, 12 Apr 2009 08:59:46


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://www.yqcomputer.com/ #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.

 
 
 

IsNumber function

Post by Sala » Sun, 12 Apr 2009 14:06:29

ark Space wrote:


Very cool. Use overload on the methods and call it.


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.
 
 
 

IsNumber function

Post by RedGrittyB » Sun, 12 Apr 2009 19:54:26


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
 
 
 

IsNumber function

Post by Andre Weih » Sun, 12 Apr 2009 21:11:29


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.
 
 
 

IsNumber function

Post by Patricia S » Sun, 12 Apr 2009 22:38:00


...
...

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
 
 
 

IsNumber function

Post by ram » Sun, 12 Apr 2009 23:11:03

Salad < XXXX@XXXXX.COM > writes:

public class Main
{
public static boolean isNumeric( final java.lang.Object object )
{ return object instanceof java.lang.Number; }

public static void main( final java.lang.String[] args )
{ java.lang.System.out.println( isNumeric( 123 ));
java.lang.System.out.println( isNumeric( "Mary" ));
java.lang.System.out.println( isNumeric( true )); }}

true
false
false
 
 
 

IsNumber function

Post by ram » Sun, 12 Apr 2009 23:30:35

Salad < XXXX@XXXXX.COM > writes:

public class Main
{
public static boolean isNumber( final java.lang.String string )
{ final java.util.Scanner scanner = new java.util.Scanner( string );
return scanner.hasNextBigInteger() || scanner.hasNextBigDecimal(); }

public static void main( final java.lang.String[] args )
{ java.lang.System.out.println( isNumber( "123" ));
java.lang.System.out.println( isNumber( "Mary" ));
java.lang.System.out.println( isNumber( "123.0" )); }}

true
false
true

(The format of 23.0depends on the locale in the above implementation.
The above output occurs with a local using as the decimal separator.)
 
 
 

IsNumber function

Post by ram » Sun, 12 Apr 2009 23:42:09

Supersedes: < XXXX@XXXXX.COM >

Salad < XXXX@XXXXX.COM > writes:

public class Main
{
public static boolean isNumber( final java.lang.String string )
{ final java.util.Scanner scanner = new java.util.Scanner( string );
return scanner.hasNexDouble(); }

public static void main( final java.lang.String[] args )
{ java.lang.System.out.println( isNumber( "123" ));
java.lang.System.out.println( isNumber( "Mary" ));
java.lang.System.out.println( isNumber( "123.0" )); }}

true
false
true

(The format of 23.0depends on the locale in the above implementation.
The above output occurs with a locale using as the decimal separator.)
 
 
 

IsNumber function

Post by ram » Sun, 12 Apr 2009 23:48:21


XXXX@XXXXX.COM (Stefan Ram) writes:

To exclude strings beginning with a number and then containing
addition text:

public class Main
{
public static boolean isNumber( final java.lang.String string )
{ final java.util.Scanner scanner = new java.util.Scanner( string );
if( scanner.hasNextDouble())
{ scanner.nextDouble(); return !scanner.hasNext(); }
else return false; }

public static void main( final java.lang.String[] args )
{ java.lang.System.out.println( isNumber( "123" ));
java.lang.System.out.println( isNumber( "Mary" ));
java.lang.System.out.println( isNumber( "123Mary" )); }}

true
false
false
 
 
 

IsNumber function

Post by Mark Spac » Mon, 13 Apr 2009 00:52:50


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.



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 de *** 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 de *** . Just sayin'....
 
 
 

IsNumber function

Post by Eric Sosma » Mon, 13 Apr 2009 02:22:23


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

--
Eric Sosman
XXXX@XXXXX.COM
 
 
 

IsNumber function

Post by Lew » Mon, 13 Apr 2009 06:15:30


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
 
 
 

IsNumber function

Post by Sala » Tue, 14 Apr 2009 10:17:07


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.