【问题标题】:How do I return an array to another class in Java?如何将数组返回给 Java 中的另一个类?
【发布时间】:2018-10-09 00:02:44
【问题描述】:

在这一点上,我只是想从我所拥有的东西中获得一些东西,但没有任何效果。

所以我从一个驱动类开始:

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

接下来我有电话课:

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

现在看起来有点荒谬,因为我已经迫不及待地想要至少拿出一些东西,而且我已经用尽了所有的想法。

应该发生的是驱动程序类给Phone一个数字,该数字将用作数组的长度(arr),并且数组用该长度初始化(数组的所有整数默认为0)并返回数组的长度与 0 一样多(或者如果我要在数组的不同位置分配不同的值,它将按照每个值在数组中的放置顺序遍历并打印每个值)。

【问题讨论】:

  • 你写你不能返回数组,因为它是私有的。为什么不复制它并返回一个副本?
  • 你的Phone 类的“吸气剂” - public Phone[] getNumber() { return arr; } 或类似的东西

标签: java arrays


【解决方案1】:

你的构造函数不会返回任何东西

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

但是你需要一个吸气剂

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

通常我会有单独的类来保存Phone 数组,而Phone 对象本身只处理实际手机的功能。

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 2019-03-15
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 2013-03-04
    相关资源
    最近更新 更多