Array problem: Int data is not fixed?
Sunday, 17-Jan-99 21:09:39
142.166.253.91 writes:
Hie, I have completed the code until this far. HOw do i continue?
import simpleIO.*;
public class problemArray extends SimpleGUI {
private int[] x;
private int[] y;
private int[] z;
public void readArray() {
x = new int[getInt("how many numbers do you want to read?")];
y = new int[getInt("how many numbers do you want to read?")];
}
the problem goes like this...
I am suppose to write a program to read data items into two arrays, x and y. store
the product of corresponding elements of x and y in a third array, z. Display a
three-column table displaying corresponding elements of the arrays x,y abd z. Then
compute and print the square root of the sum of the items in z.
AG
Re: Array problem: Int data is not fixed?
Sunday, 17-Jan-99 22:02:07
152.166.57.173 writes:
There's a problem inherent with the above code and the desired result. What if the arrays turn out to be of different lengths? Your code could possibly run into problems. But a solution that just uses the smaller array size would go as follows. (But unless there is some particular reason you implement the above method, I would assign BOTH arrays the same single size.)
You would want to determine the smallest size array. With the implementation you have above, you'd have to use a method of the reflection class to retrieve the sizes: java.lang.reflect.Array.getLength(arrayName). But this process could be simplified by storing the "getInt" results in a variable. After all that, you can execute a for loop that runs from zero and goes while the loop control variable is less than the smaller array size. Inside of the loop you would do a simple assign statement involving the three arrays and the loop control variable.
z[iLoop] = x[iLoop] * y[iLoop];
Printing the results in a table might involve using the "tab" escape sequence which I think is "\t", but I'm not sure about that.
and then printing the square root of the x values would be very similar to the method of assigning the z array, except that with in the loop you would have something like
double dSqrt = java.lang.Math.sqrt((double) x[iLoop];
Probably inconsequential, but FYI, in JDK 1.1, "java.lang.Math.sqrt(double dNum)" is a native method.
MikeD