Nadal
Nadal

Reputation: 7

Instance variables with arrays

I am trying to create an instance variable that is an array. I have many methods that will produce certain statistics about the array. I'm wondering if someone can explain to me if I am going about this the correct way. I'm rather new to Java, so any pointers is greatly appreciated. When I run the program I get errors, such like Null. I'm not looking to fix these errors now, I'm just wondering if I am going about this the correct way.

My data class:

   import java.util.Arrays;
   public class Stat {

private double data[];

public Stat()
{
    data = new double[1];
    data[0]= 0.0;
}

public Stat(double[] d)
{
    d = new double[d.length];

}

public double[] getData()
{
    return data;

}

public void setData(double[] d)
{

}

Main method:

  double[] data = {1,2,2,3,4,5};
    Stat stat1 = new Stat(data);

    System.out.println(stat1.getData());

    System.out.println("stat1 data = " + stat1.toString()); 
    System.out.println("stat1 min = " + stat1.min()); 
    System.out.println("stat1 max = " + stat1.max()); 
    System.out.println("stat1 average = " + stat1.average()); 
    System.out.println("stat1 mode = " + stat1.mode()); 
    System.out.println("stat1 data = " + stat1.toString());

Upvotes: 0

Views: 1033

Answers (2)

Naili
Naili

Reputation: 1602

Change the constructor to be

public Stat(double[] d)
{
    data = d.clone();
}

Because by using the new keyword, your are creating a new empty array. Second error, you can't print directly an array. You have to print its elements, one by one using a for loop for example. However, I suggest that you override the toString() method

@Override
public String toString(){
    return Arrays.toString(data);
}

Then printing your class will output the content of the array

System.out.println("stat1 data = " + stat1);

Upvotes: 0

Tyler
Tyler

Reputation: 18157

This constructor doesn't really do anything. You pass in an array in d, and then assign d to a different array when you say new, and additionally, d only lives on the stack until the method returns. Whenever this constructor is used data is never initialized and that's where your error is coming from.

Change:

public Stat(double[] d)
{
    d = new double[d.length];
}

to something like this:

public Stat(double[] d)
{
    data = d;
}

Here's what I ran on my computer:

public class Stat {

    private double data[];

    public Stat()
    {
        data = new double[1];
        data[0]= 0.0;
    }

    public Stat(double[] d)
    {
        data = d;

    }

    public double[] getData()
    {
        return data;

    }

}

public class JavaTest {

    public static void main(String[] args) {

        double[] data = {1,2,2,3,4,5};
        Stat stat1 = new Stat(data);

        System.out.println(stat1.getData()[0]);  //outputs 1.0

    }
}

Upvotes: 1

Related Questions