Completed Java 1, wrote a tidy bit of code:


If I’d turned in one last homework it would have been an “A”. Mia Culpa.  I nailed all the homework I did turn in- 12.5/12.5 for 1-6, but only got #7 ready to compile by the deadline.

Here’s I neat piece of code I wrote and used in a couple of places- give it a string containing a number and it will give you back the number- the base language doesn’t keep this in any obvious place, but perhaps I should check the utility library before claiming to have set them right. :^)
/* Here’s an object that packages the messy job of converting Strings that represent numbers into a double.  Int/float/double/long don’t appear to even offer a polymorphic solution. That I’ve found anyway.
Instantiate with a string,
get back a double

anything else I might want

Ok wise guy, how do you get the base classes text value??
Ah ha! String is final- no extending it! This class can HAVE one but can’t BE one
*/

public class NumericString{  // can’t “extends String” its final

String input;
Double value;
// Constructor

public void NumericString( String inputValue ) {

input = inputValue;

// later we can filter out all but the signed numeric nugget we care about…

if (-1 == input.indexOf(‘.’)) {   //only numerals, no decimal, its an integer.
value = (double) Integer.parseInt( input )
;
} else {   // there must have been a decimal, its a float/double
value = ((Double.valueOf(input).doubleValue()));
} // if -1 … else…
}

public Double num() {
return value;
}

} // class NumericString

Advertisements

2 responses to “Completed Java 1, wrote a tidy bit of code:

  1. Eric Lindberg

    Of course, you could just do

    Double value;

    try {
    value = new Double(inputString);
    }
    catch (NumberFormatException ex) {
    . . .
    }

    Then for real fun, consider localization and internationalization issues. (You need to mess with the NumberFormat class for that – I’ve never done that myself.)

    • Eric,
      Nice suggestion!
      Letting the Double constructor solve the problem is almost certainly the most robust solution.
      I need to spend more time with catching exceptions, that’s one of the homeworks I haven’t done yet!

      Bill

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s