Math operations

Hi, my data is in the form: name1 name 2 5 7 8 9 2 3

where the numbers are stored in sessions variables LEFT_NUM1, RIGHT_NUM1....LEFT_NUM2, RIGHT_NUM2....LEFT_NUM3, RIGHT_NUM3...
Is there a way I can divide left by right, and just have it output the one number, i.e. so the file would read name1 name2 0.4 ....etc

I've tried things like
left=dataRecord.get( "LEFT_NUM1" );
right=dataRecord.get("RIGHT_NUM2);
number=left/right;
out.write(number);

but to no avail, anyone know how I can do this?

Thanks

Sorry for the delayed

Sorry for the delayed response!

I'm not sure that I understand perfectly what your setup is, but I'll give it a shot and if I'm wrong you can clarify.

I'll need a better idea of what numbers are which variables, from your example. It's all on one line, which leads me to believe that you're listing them in an interwoven fashion? for example.. 2, 7, 9, and 3 are all "left" numbers, and 5,8, and 2 are all "right" numbers?

Working from that assumption... let's seee... so you want to divide left by right.. you want to add all lefts together and then all rights together, and then divide the sums? You only gave one example of the division.. Ah, but 2/5 is 0.4, so perhaps you mean divide each pair against one another, and then you end up with half as many numbers, which are the results of each division operation?

We'll work from the latter. I'll also assume that your variables are also "integer" datatypes, and not "String" datatypes.

So, what *does* happen when you write out the result? My assumption is that it's always "0", but I'm not sure... you didn't specify..... I'm assuming that you get all zeros in your output. This happens because in pretty much any programming language, one integer divided by another yields an integer (ie, the same data type that was put into the the division operation). Clearly you want more than just the "0" part of "0.4".

So try this:


for (int i = 1; dataRecord.get("LEFT_NUM"+i) != null); i++)
{
    out.write( (dataRecord.get("LEFT_NUM"+i) / (1.0 * dataRecord.get("RIGHT_NUM"+i))).toString());
}

Notice the multiplication by "1.0", which forces one of our two numbers to be a "float" type, instead of an "integer" type. The resuling division will then be a fractional number instead of just "0".

Also notice the ".toString()" on the end of the division. I'm pretty sure that sending "out.write" a floating-point number throws an error, and that the data needs to be turned back into a String for writing to your file.

My for loop is a little un-traditional; the middle part can't track how many "left" and "right" variables there are, so the loop is told to keep going as long as a variable "LEFT_NUMi" (where i is a number) exists.

I also condensed the code into just one line.. not too much of a reason to spread it out. It only makes Java even slower (call me picky).

Does that help the issue at all? Let me know if there's something I've not accounted for!

Tim