我正在为计算机科学课做作业,但我陷入了这一部分。我应该为给定的主方法和实例变量编写构造函数。构造函数需要有一个 ArrayList 和一个 Array 作为参数,但我不完全确定如何做。
使用说明及主要方法如下:
Use the comments and the code provided to complete the constructor
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();
}
}
我目前拥有的构造函数是这样的: 公共(public)矩形统计(双 w,双 l) { 宽度=w; 长度=l; 面积=0; }
但我不确定它是否正确..帮助?
最佳答案
如果你传递的实际参数是ArrayList
和array
分别,那么你的方法签名中的形式参数也应该是相同的。即:
public RectangleStats(ArrayList<Double> arg0, double[] arg1)
然后您将分配 arg0
和arg1
(或者无论你的标识符是什么)到你的实例变量。
话虽如此,实现背后的整个想法非常糟糕(例如:使用 ArrayList
和 array
而不是其中之一)。
此外,当您声明 ArrayList
时,按如下方式执行此操作:
ArrayList<Double> dblWidth = new ArrayList<Double>();
指定要添加的对象的类几乎总是更好。
关于java - ArrayList 和 Array 作为构造函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22124816/