Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# I need to put a double into a vector

Donna Bachner
Ranch Hand
Posts: 109
I have a vector and want to replace the number in the vector with a double how do I do it. This is what I have and keep getting a number format exception.

for (int m = 0; m<POInum; m++)
{
for (int n=0; n<len; n++)
{
Integer g = (Integer)POI[m].elementAt(n);
String s = g+"";

int f = Integer.parseInt(s);
double w = f * POIBottom[m];
String h = w+"";
Integer I = Integer.valueOf(h);// my error happens here

System.out.println(w);
POI[m].setElementAt(w);
System.out.println("POI"+POI[m].elementAt(n));
}
}

Ernest Friedman-Hill
author and iconoclast
Marshal
Posts: 24208
35
A double will have a decimal point in it, which isn't going to be a valid String representation of an integer. If you needed to convert a double into an int by way of a String, then you'd want to convert the double into an int first before converting to a String:

String s = ((int) w) + "";
int i = Integer.parseInt(s);

But you're doing a lot of slow, inefficient, and unnecessary conversions here. I really can't tell what you're trying to accomplish, exactly, but note that, for example, if you have an Integer object, you can use its "intValue()" method to make it into an int, without creating a String and parsing it:

Integer g = (Integer)POI[m].elementAt(n);
int f = g.intValue();

And you can make an Integer out of a double with help from a cast:

double w = f * POIBottom[m];
Integer I = new Integer((int) w);

The techniques I've shown here are much faster and more efficient, and can't give any runtime exceptions.

Donna Bachner
Ranch Hand
Posts: 109
I'll try that I know i was doing extra steps but did not know how to change it. Thanks