简体   繁体   中英

Copying columns from 2D array into object 1D array

I've been trying to copy the columns of a 2D array into a 1D array. The Stock class I created has a double[] array named data. The last loop tries to print some values that should be in the first Stock object, but it actually prints the values from the last object.

Stock arr[] = new Stock[numcols];   // creates array with the same n of slots as columns
        double[] temp = new double[numrows-1];

        for(int i=1; i<numcols; i++){
            for(int j=1; j<numrows; j++){
                temp[j-1] = fluct[j][i];
            }
            arr[i-1] = new Stock(temp, compName[i-1], price[i-1]);
        }
        for(int i=0; i<numrows/20; i++)
            System.out.println(arr[0].data[i] + arr[0].name);

In fact, if I loop printing arr[j].data[i] it will print the same values for all j. It seems the loop is creating all objects with the same values for each Stock, but I see no reason why it is doing so.

I've checked the 2D array fluct and all values there are in order. I start the loops at position 1 as the values in position 0 are of no interest. Also tried printing separately the values of temp[] and they were correct, but still the data in the objects was wrong.

Here's the Stock object (omitted the getMean/getDev methods for brevity):

public class Stock{
    public static double[] data;
    public static String name;
    public static double stDev;
    public static double price;
    public static double mean;

    public Stock(double[] newData, String newName, double newPrice){
        this.data = newData;
        this.name = newName;
        this.price = newPrice;
        this.mean = getMean();
        this.stDev = getDev();
    }
}

The problem is with were you define your temp array. You should do it inside the first for loop:

Stock arr[] = new Stock[numcols];   // creates array with the same n of slots as columns

for(int i=1; i<numcols; i++){
    double[] temp = new double[numrows-1];
    for(int j=1; j<numrows; j++){
        temp[j-1] = fluct[j][i];
    }
    arr[i-1] = new Stock(temp, compName[i-1], price[i-1]);
}
for(int i=0; i<numrows-1; i++)
    System.out.println(arr[0].data[i] + arr[0].name);

This way for every arr element a new temp will be used. Currently you are using the same temp object and it's values are being updated as well as the values for arr elements. Also I've changed to condition for the last for loop to i<numrows-i . Don't know why you needed i<numrows/20 =)

Good luck with Java studying!

Well, this is embarrassing, but I finally figured out what was wrong. In my object class I had my variables static! Removing that solved it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM