简体   繁体   中英

Passing an array of double value from one java class to another

I have an Java class file that contains an array of double values that I wanted to use in another Java class file. This is the simplified version of my code:

File1.java

public class File1.java{

//code

public void compute
{
    double[] vectorX_U = {0.1, 0.2, 0.5}
}

//i tried this method to pass but it said vectorX_U cannot be resolved to a variable
 public Double[] getvectorX_U() 
 {
     return vectorX_U;
 }

File2.java

//i attempt to use the array
public void computethis
{
    File1 td = new File1();
    System.out.println(td.getvectorX_U());
}

Can I have some help on how to achieve this? Thanks!

Your File1 is riddled with errors.

Basically (besides the compilation errors), you need to have your array of doubles as an instance variable.

As it is now, it is a local variable within the compute method, and your get method has no access to it.

File1.java

public class File1{ // no .java here!

double[] vectorX_U;

public void compute
{
    vectorX_U = {0.1, 0.2, 0.5}
}


 public Double[] getvectorX_U() 
 {
     return vectorX_U; // now it will find the instance variable
 }
}

EDIT:

you will need to call the compute method before calling the getvectorX_U, though. If you don't, the array will not be initialized, and the getter will return null.

if you don`t want change the arrays value and all the class can use it as "global variable" you can set

public class File1.java{

   public static final double[] VECTORX_U = {0.1, 0.2, 0.5};

   ............

}

if you want change it and every this variable in instances are same

public class File1.java{

   static double[] vectorX_U = {0.1, 0.2, 0.5};

   ............

}

if variable in every instance of this class has a special value

public class File1.java{

   double[] vectorX_U = {0.1, 0.2, 0.5};

   ............

}

for the first and second you can use File1.variable ,the third you need create a instance of this class then you can use it

Basically your vectorX_U variable's scope is inside the compute method. So non of other methods can access the vectorX_U variable. so it should be a global variable.

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