2014-03-02 32 views
0

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

的指导和主要方法如下:

使用提供完成构造

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

     } 

    } 

我目前拥有的构造函数的注释和代码是这样的: 公共RectangleStats (双w,双l) 宽度= w; length = 1; area = 0; }

但我不知道如果它的权利或不..帮助?

+0

你的构造函数在哪里? – Kakarot

+0

这就是我要弄清楚..我写下了我认为的构造应该是,但即时通讯不太确定.. – user3164890

回答

2

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

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

你可以这样分配arg0arg1(或任何你标识符)到您的实例变量。这就是说,实施背后的整个想法很差(例如:使用ArrayListarray而不是其中之一)。

此外,当你宣布你ArrayList,做法如下: ArrayList<Double> dblWidth = new ArrayList<Double>();

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

+0

感谢您的答案 是的,我猜测使用它们的实现并不是那么好,但不幸的是,我不是提出问题的人:/ – user3164890

+0

没问题。我知道这是家庭作业,你不能改变你的老师的问题,但是如果你有兴趣,有一个'宽度'和'长度'参数的'Rectangle'类会更有意义 - 那么你可以简单地声明一个拥有其中2个元素的数组,而不是拥有一个对象,比如你的问题中的一个元素拥有两个矩形宽度和两个长度(这使得它更不合理)。 – ujvl

2

有了一个好的java的书或者你可能有教程轻松解决你的问题,但是这是你会怎么做:

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

{ 

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

+0

感谢您的回答! – user3164890