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

时间:2016-03-01 06:58:56

标签: java

我有一个Java类文件,其中包含我想在另一个Java类文件中使用的double值数组。这是我的代码的简化版本:

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());
}

我可以帮忙解决一下这个问题吗?谢谢!

3 个答案:

答案 0 :(得分:4)

你的File1充满了错误。

基本上(除编译错误外),您需要将您的双精度数组作为实例变量。

现在,它是compute方法中的局部变量,并且你的get方法无法访问它。

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
 }
}

编辑:

但是,在调用getvectorX_U之前,您需要调用compute方法。 如果你没有,那么数组将不会被初始化,并且getter将返回null。

答案 1 :(得分:0)

如果您不想更改数组值,并且所有类都可以将其用作"全局变量"你可以设置

An exception of type 'System.InvalidCastException' occurred in ...Data.dll but was not handled in user code

Additional information: Specified cast is not valid.

如果你想改变它,实例中的每个变量都是相同的

public class File1.java{

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

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

}

如果此类的每个实例中的变量都具有特殊值

public class File1.java{

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

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

}

对于第一个和第二个你可以使用File1.variable,第三个你需要创建这个类的实例然后你可以使用它

答案 2 :(得分:-1)

基本上你的vectorX_U变量的范围在compute方法中。因此,其他方法不能访问vectorX_U变量。所以它应该是一个全局变量。

相关问题