如何将数组返回到Java中的另一个类? [英] How do I return an array to another class in Java?

查看:115
本文介绍了如何将数组返回到Java中的另一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这一点上,我只是想从我所没有的东西中得到一些东西,而无济于事。



所以我从驱动程序类开始:

  class TheDriverClass 
{
public static void main(String [] args)
{
电话p =新电话(5);
System.out.println(p);
//这里应该返回大小为5的数组的值,
//因此应该打印出00000
}
}

接下来我上课了:

  class Phone 
{
private Phone [] arr; //我应该将数组设为私有
public Phone(int theLength){
arr = new Phone [theLength];
return Arrays.toString(arr);
}
}

现在看起来有点荒谬,因为我已经成为迫切希望至少了解一些东西,而我已经用尽了所有想法。作为数组的长度(arr),并使用该长度初始化数组(数组的所有整数默认为0),并返回与数组长一样多的0(或者如果我要在数组的不同位置分配不同的值)数组,它将按照排列在数组中的顺序遍历并打印每个值。)

解决方案

您的构造函数将

 公用电话(int theLength){
arr =新电话[theLength];
}

但是您将需要使用吸气剂

 公用电话[] getPhones(){
return arr;
}

通常,我会有单独的类来容纳 Phone 数组和 Phone 对象本身仅处理实际电话的功能。


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).

解决方案

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.

这篇关于如何将数组返回到Java中的另一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆