Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / May 2008

Tip: Looking for answers? Try searching our database.

True Integer, Double

Thread view: 
RC - 12 May 2008 15:50 GMT
Heaveno (Not Hello),

How do I make sure a number is a TRUE Integer or TRUE Double?

i.e
Integer integer = new Integer("1"); // TRUE

Integer integer = new Integer("1.0");
// NOT TRUE, NumberFormatException couldn't catch it

Double d = new Double("1.0"); // TRUE

Double d = new Double("1");
// NOT TRUE, NumberFormatException couldn't catch it

Thank Q very much in advance!
Kenneth P. Turvey - 12 May 2008 16:00 GMT
> Heaveno (Not Hello),
>
[quoted text clipped - 12 lines]
>
> Thank Q very much in advance!

I would look at using a regular expression to match the Strings.  

See String#matches()

Signature

Kenneth P. Turvey <kt-usenet@squeakydolphin.com>

Stefan Ram - 12 May 2008 16:02 GMT
>How do I make sure a number is a TRUE Integer or TRUE Double?
>Thank Q very much in advance!

 I might be able to answer as soon as »TRUE Integer« is defined.
Eric Sosman - 12 May 2008 16:10 GMT
> Heaveno (Not Hello),
>
[quoted text clipped - 10 lines]
> Double d = new Double("1");
> // NOT TRUE, NumberFormatException couldn't catch it

    I'm not quite sure what you mean by "TRUE," since "1"
seems like a perfectly good Integer to me, just as "1.0"
and "1" seem like perfectly good Doubles.

    I'm also perplexed at "NumberFormatException couldn't
catch it."  In the case of `new Double("1")' there should be
no exception thrown, because there's nothing wrong with "1"
as a Double.  But for `new Integer("1.0")' there should be a
NumberFormatException, and you should be able to catch it if
you want to.

    Try explaining your notion of "TRUE" a bit more, and/or
consider using java.text.NumberFormat.

Signature

Eric.Sosman@sun.com

RC - 12 May 2008 16:35 GMT
>     Try explaining your notion of "TRUE" a bit more, and/or
> consider using java.text.NumberFormat.

I have some text data look like this (written by some
retiree in Fortran)
I need to convert them into XML file

1295   1     38.23     39.26     41.10     43.82     47.50     45.29

Which means data starts from
<event data="1995-12-1 00:00:00" value="38.23" />
<event data="1995-12-1 06:00:00" value=" 39.26" />
<event data="1995-12-1 12:00:00" value=" 41.10" />
<event data="1995-12-1 18:00:00" value=" 43.82" />
<event data="1995-12-2 00:00:00" value=" 47.50" />
<event data="1995-12-2 06:00:00" value=" 45.29" />

Now, you can see column 0 and column 1(1st and 2nd columns)
are TRUE Integer.
After column 2 (3rd column) are TRUE Double.
Stefan Ram - 12 May 2008 16:45 GMT
>Now, you can see column 0 and column 1(1st and 2nd columns)
>are TRUE Integer.

 A common kind of question/dialogs in this newsgroup
 goes like:

     A:  A text like »egnor« is an alpha, while a
         text like »aeowr« is a beta. Now, I need
         a program or a regular expression to tell
         whether any given text is an alpha or a beta.

     B:  Could you define what is an alpha?

     A:  Well, yes, it is a text like »egnor«,
         but not a text like »aeowr«, you see?

 Wild guess:

 The simplest solution for you might be String#contains( "." ).
Eric Sosman - 12 May 2008 17:10 GMT
>>     Try explaining your notion of "TRUE" a bit more, and/or
>> consider using java.text.NumberFormat.
[quoted text clipped - 16 lines]
> are TRUE Integer.
> After column 2 (3rd column) are TRUE Double.

    And your problem with this is ...?  Perhaps I'm just being
dense today, but I don't see the difficulty.  If you know that
columns 0 and 1 hold integers, use `new Integer(data[0])' or
`Integer.parseInt(data[1])'.  For the remaining columns use
`new Double(data[2])' or `Double.parseDouble(data[3])'.  In
both cases, you can try/catch NumberFormatException to detect
trouble if desired.

    If you just want to rearrange the data and don't need to
validate it, most of the conversions may be unnecessary anyhow.
I guess you'll want to convert the first two columns and build
a Calendar object from them (it's easy to keep adding six-hour
intervals to a Calendar), but you could just take the remaining
columns as strings, outputting them in the same form they were
read.

Signature

Eric.Sosman@sun.com

John B. Matthews - 12 May 2008 18:54 GMT
[...]
> I have some text data look like this
> (written by some retiree in Fortran)

Indeed.

[...]
> 1295   1     38.23     39.26     41.10     43.82     47.50     45.29
[...]

A suitable abstraction might be java.lang.Number. The parse() method of
java.text.DecimalFormat should suffice.
Wojtek - 12 May 2008 19:08 GMT
RC wrote :

>>     Try explaining your notion of "TRUE" a bit more, and/or
>> consider using java.text.NumberFormat.
[quoted text clipped - 16 lines]
> are TRUE Integer.
> After column 2 (3rd column) are TRUE Double.

Try to create an Integer, and if that fails then assume it is a Double.

Signature

Wojtek :-)

Mark Space - 12 May 2008 21:25 GMT
> RC wrote :

>> I need to convert them into XML file
>>
>> 1295   1     38.23     39.26     41.10     43.82     47.50     45.29

> Try to create an Integer, and if that fails then assume it is a Double.

No that won't work.  The OP already showed us that trying to create an
Integer from float-string succeeds.

RC, I think what you want to do is *validate* your data before you try
to parse it.

If the data must contain only decimal digits, use a regex to match that
before you call Integer.parse().  If the data must contain at least one
"." and one decimal digit, then use a regex to verify that fact, again
before calling Double.parse().

Parse() doesn't validate data, I guess, just parses it.  Validation you
do yourself.
Eric Sosman - 12 May 2008 21:45 GMT
>> RC wrote :
>
[quoted text clipped - 6 lines]
> No that won't work.  The OP already showed us that trying to create an
> Integer from float-string succeeds.

    If that's what he was trying to say, he was mistaken.
On Java 1.6.0_05-b13, `new Integer("1.0")' gives me

Exception in thread "main" java.lang.NumberFormatException: For input
string: "1.0"

... so I don't think his "NumberFormatException couldn't catch
it" meant "No exception is thrown."  (What it *did* mean is a
mystery he's declined to elucidate.)

> Parse() doesn't validate data, I guess, just parses it.  Validation you
> do yourself.

    If he uses the parse() method of a suitable integer-only
NumberFormat, it will stop on a '.' rather than objecting to
it.  But according to his original method, that's not what he
was doing: He was using the Integer(String) constructor, which
insists on converting the entire String, not just a prefix.

Signature

Eric.Sosman@sun.com

Mark Space - 13 May 2008 01:21 GMT
>     If that's what he was trying to say, he was mistaken.
> On Java 1.6.0_05-b13, `new Integer("1.0")' gives me
>
> Exception in thread "main" java.lang.NumberFormatException: For input
> string: "1.0"

Huh, so he did.  I'm honestly not sure where I got that idea. Sorry
about that.

Still, I like the idea of a general data validator.  Seems cleaner, and
possibly faster, than just throwing exceptions.
Arne Vajhøj - 13 May 2008 01:48 GMT
>>     If that's what he was trying to say, he was mistaken.
>> On Java 1.6.0_05-b13, `new Integer("1.0")' gives me
[quoted text clipped - 7 lines]
> Still, I like the idea of a general data validator.  Seems cleaner, and
> possibly faster, than just throwing exceptions.

That should only be relevant if errors happen frequently and the program
logic requires the program to continue running.

But validating via regex should be relative easy, so no problem
doing that either.

Arne
RC - 13 May 2008 15:07 GMT
>     If that's what he was trying to say, he was mistaken.
> On Java 1.6.0_05-b13, `new Integer("1.0")' gives me
[quoted text clipped - 5 lines]
> it" meant "No exception is thrown."  (What it *did* mean is a
> mystery he's declined to elucidate.)

We are not allows to use 1.6.x, yet.
Currently all our projects MUST use 1.5.x

Thank Q for all of u.
P.S.
The reason I DON'T want to use

new Integer("1");
and
new Double("1.0");
is:

the text format sometime is

1295   1     38.23     39.26     41.10     43.82     47.50     45.29

The data starts at column 2 (3rd column)
But some time is

JOSNC       0393  29    14.17

The data starts at column 3(4th column), also the 1st column is a string.

There are more formats to come (U know those Fortran programmers during
70's). We have to clean up their mess, all into XML format.
Eric Sosman - 13 May 2008 15:46 GMT
>>     If that's what he was trying to say, he was mistaken.
>> On Java 1.6.0_05-b13, `new Integer("1.0")' gives me
[quoted text clipped - 8 lines]
> We are not allows to use 1.6.x, yet.
> Currently all our projects MUST use 1.5.x

    Um, what does that have to do with anything?  *ALL* of

    java.lang.NumberFormatException
    java.text.NumberFormat
    java.text.DecimalFormat
    java.util.regex.Pattern
    java.util.regex.Matcher

... have been around since Java 1.4 if not earlier.

Signature

Eric.Sosman@sun.com

Lew - 14 May 2008 00:39 GMT
>>>     If that's what he was trying to say, he was mistaken.
>>> On Java 1.6.0_05-b13, `new Integer("1.0")' gives me
[quoted text clipped - 18 lines]
>
> .... have been around since Java 1.4 if not earlier.

Plus, Java 5 enters its End-of-Life phase in a few months.

Signature

Lew

Lew - 14 May 2008 00:39 GMT
> Thank Q for all of u.

While Q certainly has God-like powers, one should remember that he is, after
all, a fictional character.
<http://en.wikipedia.org/wiki/Q_%28Star_Trek%29>

You might want to thank those who actually gave you some "u" (whatever that
is), rather than to thank a non-existent not-quite-Supreme being.

In other words, drop the illiterate and ridiculous "txtspeak".

Signature

Lew

Arne Vajhøj - 15 May 2008 01:13 GMT
>>     If that's what he was trying to say, he was mistaken.
>> On Java 1.6.0_05-b13, `new Integer("1.0")' gives me
[quoted text clipped - 8 lines]
> We are not allows to use 1.6.x, yet.
> Currently all our projects MUST use 1.5.x

> The reason I DON'T want to use
>
[quoted text clipped - 13 lines]
>
> The data starts at column 3(4th column), also the 1st column is a string.

That is not a reason not to use those - you just need to check data
before calling them.

There are other reasons why I would not use those, but ...

> There are more formats to come (U know those Fortran programmers during
> 70's). We have to clean up their mess, all into XML format.

So far I have not seen any indication of that they have not done
a good job - it is not their faults that some of todays programmers
seems to have problems with extremely simple tasks.

Arne
Tim Smith - 18 May 2008 06:21 GMT
> We are not allows to use 1.6.x, yet.
> Currently all our projects MUST use 1.5.x
[quoted text clipped - 21 lines]
> There are more formats to come (U know those Fortran programmers during
> 70's). We have to clean up their mess, all into XML format.

So, you are dealing with a bunch of messy text formats, with special
cases and such, that need to be cleaned up?

Are you *required* to use Java for this?  Your problem seems to be
getting into the realm where Perl might be more convenient.  This is the
kind of thing it was designed for.

Signature

--Tim Smith

Tom Anderson - 18 May 2008 13:29 GMT
>> The reason I DON'T want to use
>>
[quoted text clipped - 23 lines]
> getting into the realm where Perl might be more convenient.  This is the
> kind of thing it was designed for.

Perl was designed? I thought Larry Wall just found it growing under a log
one day.

tom

Signature

1 p4WN 3v3Ry+h1n G!!!

Tim Smith - 18 May 2008 23:24 GMT
> > Are you *required* to use Java for this?  Your problem seems to be
> > getting into the realm where Perl might be more convenient.  This is the
> > kind of thing it was designed for.
>
> Perl was designed? I thought Larry Wall just found it growing under a log
> one day.

Haha, but my suggestion was serious.  For the first format he proposed,
this is what I think he wants:

#!/usr/bin/perl
use strict;
use POSIX qw(strftime);

while (<>) {
   chomp;
   s/^\s+//;
   s/\s+$//;
   my($mmyy,$day,@values) = split /\s+/;
   my($month,$year) = $mmyy =~ /(\d+?)(\d\d)$/;
   my $hour = 0;
   foreach my $value (@values) {
       my $time_string = strftime "%Y-%m-%d %H:%M:%S", 0, 0, $hour,
               $day, $month-1, $year;
       print qq{<event data="$time_string" value="$value" />\n};
       $hour += 6;
   }
}

It gives this output for his sample line:

<event data="1995-12-01 00:00:00" value="38.23" />
<event data="1995-12-01 06:00:00" value="39.26" />
<event data="1995-12-01 12:00:00" value="41.10" />
<event data="1995-12-01 18:00:00" value="43.82" />
<event data="1995-12-02 00:00:00" value="47.50" />
<event data="1995-12-02 06:00:00" value="45.29" />

It deviates slightly from exactly what he asked for, in that it prints
month and day with a leading 0 if they are less than 10, but I suspect
that is OK.  (And if not, it can be fixed easily).  I am also assuming
all the data is from before 2000, which seems likely.  If not, that can
be fixed easily, but he didn't say how dates past 1999 are recorded in
the original data.

He's going from data in a text form (flat file), to data in a text form
(XML), so I think it arguably makes sense to treat it as much as you can
as a text transformation, and not get into the issues he's getting into
of integers versus floating point.  Transform the text as
straightforwardly as possible into XML, and then, if he wants to also
validate format, he can supply an XML schema that specifies the formats
of the attributes and validate against that.

Signature

--Tim Smith

Arne Vajhøj - 12 May 2008 23:41 GMT
>> Try to create an Integer, and if that fails then assume it is a Double.
>
[quoted text clipped - 11 lines]
> Parse() doesn't validate data, I guess, just parses it.  Validation you
> do yourself.

Did he show that ?

Have you tried ?

Arne
Arved Sandstrom - 12 May 2008 20:56 GMT
>>     Try explaining your notion of "TRUE" a bit more, and/or
>> consider using java.text.NumberFormat.
[quoted text clipped - 16 lines]
> are TRUE Integer.
> After column 2 (3rd column) are TRUE Double.

The first two numbers in the text file written by the retiree are probably
header lines, something pretty commonly used in flat files by us geriatric
types. The usual way of handling a situation like this is to understand the
format of the file, read the header if necessary (and use it if necessary -
these two values are probably # of data values and maybe # of fields), and
then read all the data, *knowing* that the data are floating point.

AHS
RedGrittyBrick - 12 May 2008 22:54 GMT
>>>     Try explaining your notion of "TRUE" a bit more, and/or
>>> consider using java.text.NumberFormat.
[quoted text clipped - 22 lines]
> these two values are probably # of data values and maybe # of fields), and
> then read all the data, *knowing* that the data are floating point.

I took the 1295 to mean month 12 of year (19)95 rather than # data
values. The 1 is then the day of month. The following decimal values are
at 6 hour intervals. This corresponds with the XML fragment.

Signature

RGB

Arne Vajhøj - 12 May 2008 23:45 GMT
> I have some text data look like this (written by some
> retiree in Fortran)
[quoted text clipped - 13 lines]
> are TRUE Integer.
> After column 2 (3rd column) are TRUE Double.

That looks completely trivial to me.

Any retiree should be able to code that in 5 minutes.

Maybe you should find one and ask for help.

You can do it in so many different ways.

Integer parseInt and Double parseDouble

Scanner hasNextInt/hasNextDouble/nextInt/nextDouble

do everything using String's

etc.

Arne
Patricia Shanahan - 13 May 2008 01:06 GMT
>> I have some text data look like this (written by some
>> retiree in Fortran)
[quoted text clipped - 15 lines]
>
> That looks completely trivial to me.
...

In so far as there is any difficulty, it lies in lack of specification.
What is the syntax for a "TRUE Integer"? What is the syntax for a "TRUE
Double"? Is there any overlap between them, and if so what should be
done with strings in the overlap? Is internationalization required?

Patricia
Arne Vajhøj - 13 May 2008 01:45 GMT
>>> I have some text data look like this (written by some
>>> retiree in Fortran)
[quoted text clipped - 21 lines]
> Double"? Is there any overlap between them, and if so what should be
> done with strings in the overlap? Is internationalization required?

But using standard free format integer and decimal with period as
decimal separator will probably be OK and will certainly be a good
starting point for enhancements.

Arne
Roedy Green - 12 May 2008 21:28 GMT
>How do I make sure a number is a TRUE Integer or TRUE Double?

what constitutes a integer or double in Java source is different that
in data.  Data is laxer since you KNOW the type to be coerced to.

However if you wanted to enforce stricter rules, write a regex to
describe your allowed patterns (e.g. precise number of decimal
places), or see what effects you can get with a DecimalFormat and a
mask using the parse method.

See http://mindprod.com/jgloss/regex.html
http://mindprod.com/jgloss/decimalformat.html
Signature


Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.