0
int n = 10;
double[] x = {2.5,0.5,2.2,1.9,3.1,2.3,2,1,1.5,1.1};
double[] y = {2.4,0.7,2.9,2.2,3.0,2.7,1.6,1.1,1.6,0.9};

double sumx = 0.0, sumy = 0.0, sumx2 = 0.0;
for(int i = 0; i < n; i++) {
    sumx += x[i];
    sumy += y[i];
}

double xbar = sumx / n;
double ybar = sumy / n;

I have 2 results for mean values of x and y now I want to create a new array but this new array should include for example:

double[] x1 =[2.5-xbar,0.5-xbar,.....];
double[] x2 =[2.4-ybar,0.7-ybar,.....];

I want to get those arrays by using any loop and i tried to build but couldn't success. My codes:

double[] xadj = new double[10],yadj = new double[10];
for(int i=0;i<n-1;i++){
    xadj[i]+=x[i]-xbar;
    yadj[i]+=y[i]-ybar;
}

System.out.println(xadj);
System.out.println(yadj);

[OUTPUT]:

[D@17dfafd1
[D@5e8fce95

How can I overcome this issue?

Mitesh Pathak
  • 1,306
  • 10
  • 14

3 Answers3

1

System.out.println(xadj);

System.out.println(yadj);

You are printing reference to array and hence the output.

Try iterating over array and print each element or use Arrays.toString() to print

Every object has a toString() method, and the default method is to display the object's class name representation, then "@" followed by its hashcode. So what you're seeing is the default toString() representation of an array.

Refer [1] Java arrays printing out weird numbers, and text

Community
  • 1
  • 1
Mitesh Pathak
  • 1,306
  • 10
  • 14
1

Your "results" are the memory addresses of the xadj and yadj objects in memory because you simply printed out the reference to the object and not each of the cells within that object. Easiest beginner's way to do this is by using another for loop to print the results.

Instead of:

System.out.println(xadj);
System.out.println(yadj);

Try:

for(int i = 0; i < n; i++) {
    System.out.println(xadj[i]);
    System.out.println(yadj[i]);
}
bunting
  • 687
  • 1
  • 6
  • 11
1

You can use Arrays.toString(double[])

Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). Elements are converted to strings as by String.valueOf(double). Returns "null" if a is null.

But you have some rare things in your code. Use array.length instead of hardcoded n. Also you don't have to += only assign with =

double[] xadj = new double[10],yadj = new double[10];
        for(int i=0;i< x.length ;i++){
            xadj[i]=x[i]-xbar;
            yadj[i]=y[i]-ybar;
        }

        System.out.println(Arrays.toString(xadj));
        System.out.println(Arrays.toString(xadj));

What you are seeing with this

[D@17dfafd1

array toString() on a double array prints the type of the array ([D) followed by its hashCode.

nachokk
  • 14,363
  • 4
  • 24
  • 53