将数组传递给不同的类... Netbeans Java

时间:2016-03-04 19:26:31

标签: java arrays class

A.java

public Class A
{

        String a,b;
        public static void setArray(String[] array)//This is where i want the array to come
        {
               array[0]=a;
               array[1]=b
        }
}

B.java

public class B
{

        String[] arr1 = new String[2];
        arr1[0]="hello";
        arr1[2]="world";
        public static void main(String[] args)
              {
                A a = new A();
                a.setArray(arr1);//This is from where i send the array
              }
}

我正在尝试将一个数组从一个类发送到另一个类

2 个答案:

答案 0 :(得分:1)

我已经编辑了一下你的代码。你的主要问题是在A类,你在那里向后分配值。请参阅更新的A类。我还在您的课程中添加了一个构造函数,但这不是必需的。

public Class A {

  String a,b;

  // A public method with no return value
  // and the same name as the class is a "class constructor"
  // This is called when creating new A()
  public A(String[] array) 
  {
    setArray(array) // We will simply call setArray from here.
  }

  private void setArray(String[] array)
  {
    // Make sure you assign a to array[0],
    // and not assign array[0] to a (which will clear this array)
    a = array[0];
    b = array[1];
  }
}

public class B {
  String[] arr1 = new String[2];
  arr1[0]="hello";
  arr1[2]="world";
  // A a; // You can even store your A here for later use.
  public static void main(String[] args)
  {
    A a = new A(arr1); // Pass arr1 to constructor when creating new A()
  }
}

答案 1 :(得分:0)

您获得的是NULL值,因为A类中的String变量未初始化。

在A类中,您需要从方法中删除STATIC,并使用某些内容初始化String a和b,如下所示:

public class B {
    static String[] arr1 = {"hello", "world"};
    public static void main(String[] args) {
        A a = new A();
        a.setArray(arr1);//This is from where i send the array
        System.out.println(arr1[0] + " " + arr1[1]);
    }
}

在B类中,您应该将STATIC添加到数组中(不能在静态方法中引用非静态变量)。

String[] arr1 = new String[2];
arr1[0]="hello";
arr1[2]="world";

此外,如果您想以您的方式(在方法之外)初始化某些内容:

String[] arr1 = new String[2];
{
    arr1[0] = "hello";
    arr1[2] = "world";
}

你必须将初始化放在一个块中,如下所示:

def only_evens(lst):
    return filter(lambda ls: all(map(lambda n: not n & 1, ls)), lst)

希望这有助于你