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

2 responses so far ↓
Eric Lindberg // June 24, 2009 at 2:46 pm |
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.)
Bill Abbott // June 24, 2009 at 4:24 pm |
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