简体   繁体   English

如何将数组返回到Java中的另一个类?

[英]How do I return an array to another class in Java?

At this point I'm just trying to get something to come out of what little I have and nothing is working. 在这一点上,我只是想从我所没有的东西中得到一些东西,而没有任何效果。

So I start out with a driver class: 因此,我从驱动程序类开始:

    class TheDriverClass
    {
      public static void main(String[] args)
      {
        Phone p = new Phone(5);
        System.out.println(p); 
  // Here it's supposed to return the values of an array with size 5, 
  //so it should print out 00000
       }
     }

Next I have the class Phone: 接下来,我有电话课:

   class Phone
   {
       private Phone[] arr; //I'm supposed to keep the array private
       public Phone(int theLength){
          arr = new Phone[theLength];
          return Arrays.toString(arr);
       }
   }

Now it looks a little ridiculous because I've become desperate to get at least SOMETHING out and I've exhausted any and all ideas. 现在看起来有些荒谬,因为我迫切希望至少了解一些东西,而且我已经用尽了所有想法。

What is supposed to happen is that the driver class gives Phone a number which will be used as theLength of the array (arr), and the array is initialized with that length (all integers of the array defaulted to 0) and returns as many 0's as the array is long (or if I were to assign different values at different locations of the array, it will go through and print every value in the order it is placed in the array). 应该发生的是,驱动程序类为Phone提供了一个数字,该数字将用作数组的长度(arr),并使用该长度初始化数组(数组的所有整数默认为0),并返回多个0由于数组很长(或者如果我要在数组的不同位置分配不同的值,它将按照每个值在数组中的排列顺序进行打印)。

Your constructor will not be returning anything 您的构造函数将不会返回任何东西

public Phone(int theLength){
      arr = new Phone[theLength];
}

But you will need a getter 但是你需要一个吸气剂

public Phone[] getPhones () {
    return arr;
}

Usually I would have separate classes that hold the Phone array and the Phone Object itself only deals with the functionality of the actual phone. 通常,我会有单独的类来保存Phone数组,而Phone Object本身仅处理实际电话的功能。

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

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