简体   繁体   English

将一个double值数组从一个java类传递给另一个java类

[英]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. 我有一个Java类文件,其中包含我想在另一个Java类文件中使用的double值数组。 This is the simplified version of my code: 这是我的代码的简化版本:

File1.java 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 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. 您的File1充满了错误。

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. 就像现在一样,它是compute方法中的局部变量,并且get方法无法访问它。

File1.java 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. 但是,在调用getvectorX_U之前,您需要调用compute方法。 If you don't, the array will not be initialized, and the getter will return null. 如果不这样做,则不会初始化该数组,并且getter将返回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 对于第一个和第二个,您可以使用File1.variable,第三个您需要创建此类的实例然后您可以使用它

Basically your vectorX_U variable's scope is inside the compute method. 基本上你的vectorX_U变量的范围在compute方法中。 So non of other methods can access the vectorX_U variable. 因此,其他方法不能访问vectorX_U变量。 so it should be a global variable. 所以它应该是一个全局变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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