我正在努力了解构造函数和方法的工作原理。我几乎有这些概念,只是我不知道如何设置它们。我特别不知道如何在ArrayLists中使用它们。
我正在尝试计算并打印矩形区域,评论的部分是我不知道如何设置的。
import java.util.ArrayList;
class RectangleStats
{
// Private instance variables
// length is an ArrayList which will contain integer values, width is an array which will contain integer
// values, and area is an array which will contain decimal values.
//code goes here for instance variables goes here
// The constructor for the RectangleStats class takes an ArrayList and an array as parameters for
// length and width, respectively.
// code for constructor goes here
// The calcRectangleArea() method calculates the area of rectangles using the length and
// the width assigned to the private instance variables and assigns the results to the area array of type
// double. This method does not return anything.
// code for the calcRectangleArea() method goes here
// The printArea() method prints the values assigned to the area array using the most appropriate
// type of loop. This method does not return anything.
// code for the printArea() method goes here
}
// The RectangleStatsTesterClass assigns the length of two rectangles to an ArrayList and assigns the
// width 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 RectangleStatsTesterClass2
{
public static void main(String[] args)
{
ArrayList intLength = new ArrayList();
intLength.add(7);
intLength.add(5);
int [ ] intWidth = {3, 4};
RectangleStats rectStats = new RectangleStats(intLength, intWidth);
rectStats.calcRectanglePerimeter();
rectStats.printArea();
}
}
答案 0 :(得分:0)
试试这样:
import java.util.ArrayList;
import java.util.List;
class RectangleStats
{
private List<Integer> length;
private int[ ] width;
double areas[];
RectangleStats(List<Integer> length, int[] width){
this.length = length;
this.width = width;
this.areas = new double[this.width.length];
}
private void calcRectangleArea(){
for(int i=0; i<width.length; i++){
areas[i] = length.get(i) * width[i];
}
}
public void printArea(){
calcRectangleArea();
for(int i=0; i<areas.length; i++){
System.out.println("Area " + i + " : " + areas[i]);
}
}
public void calcRectanglePerimeter(){
for(int i=0; i<width.length; i++){
System.out.println("Parameter for "+ i +"th Rectangle : " + (2 * (length.get(i) + width[i])));
}
}
}
public class RectangleStatsTesterClass2
{
public static void main(String[] args)
{
ArrayList<Integer> intLength = new ArrayList<Integer>();
intLength.add(7);
intLength.add(5);
int [ ] intWidth = {3, 4};
RectangleStats rectStats = new RectangleStats(intLength, intWidth);
rectStats.calcRectanglePerimeter();
rectStats.printArea();
}
}