【问题标题】:ArrayList and Array as parameters for ConstructorArrayList 和 Array 作为构造函数的参数
【发布时间】:2014-03-02 06:57:46
【问题描述】:

我正在为我的计算机科学课做作业,但我被困在了这一部分。我应该为给定的 main 方法和实例变量编写构造函数。构造函数需要有一个 ArrayList 和一个 Array 作为参数,但我不完全确定如何。

说明及主要方法如下:

使用cmets和提供的代码完成构造函数

import java.util.ArrayList;
class RectangleStats
 { 
 //instance variables go here

 //The constructor for the RectangleStats class takes an ArrayList and an array as parameters for

 // width and length, respectively.


 // code for constructor goes here
 // The RectangleStatsTesterClass assigns the width of two rectangles to an ArrayList and assigns the
 // length of two rectangles to an array. The calcRectangleArea() and printArea() methods are invoked to 
 // calculate and print the area of the two rectangles.
 public class RectangleStatsTesterClass 
 { 
       public static void main(String[] args)

 {

       ArrayList dblWidth = new ArrayList();

       dblWidth.add(5.2);

       dblWidth.add(9.3);

       double [ ] dblLength = {11.1, 4.7};


       RectangleStats rectStats = new RectangleStats(dblWidth, dblLength);


       rectStats.calcRectangleArea();

       rectStats.printArea();

       }

  }

我目前拥有的构造函数是这样的: 公共矩形统计(双 w,双 l) { 宽度 = w; 长度 = l; 面积=0; }

但我不确定它是否正确.. 帮助?

【问题讨论】:

  • 你的构造函数在哪里?
  • 嗯,这就是我要弄清楚的......我写下了我认为构造函数应该是什么,但我不太确定......

标签: java arrays arraylist parameters constructor


【解决方案1】:

如果您传递的实际参数分别是ArrayListarray,那么您的方法签名中的形式参数也应该相同。那就是:

public RectangleStats(ArrayList<Double> arg0, double[] arg1)

然后,您可以将 arg0arg1(或任何您的标识符)分配给您的实例变量。

话虽如此,实现背后的整个想法非常糟糕(例如:使用ArrayListarray 而不是其中之一)。

另外,当您声明您的 ArrayList 时,请执行以下操作: ArrayList<Double> dblWidth = new ArrayList<Double>();

指定要添加的对象的类几乎总是更好。

【讨论】:

  • 感谢您的回答是的,我想使用它们的实现并不是那么好,但不幸的是我不是提出问题的人:/
  • 没问题。我知道这是家庭作业,您不能更改老师的问题,但如果您有兴趣,使用带有 widthlength 参数的 Rectangle 课程会更有意义 - 然后您可以简单地声明一个包含其中 2 个的数组,而不是让一个对象(例如您的问题中的那个)来保存两个矩形宽度和两个长度(这没有多大意义)。
【解决方案2】:

有了一本好的 Java 书籍或教程,您可能很容易解决您的问题,但这就是您的做法:

ArrayList<Double> w;
double []length;
public RectangleStats(ArrayList<Double> width, double length[])
 { 
     this.width = width;
     this.length = length;

 {

我猜这些变量是在构造函数之外使用的,因此是初始化。

【讨论】:

  • 感谢您的回答!
猜你喜欢
  • 1970-01-01
  • 2016-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-31
  • 2014-05-02
  • 2013-12-20
相关资源
最近更新 更多