早上好,如果这个问题很复杂/令人困惑,我道歉。我参加了一个简介java课程,我的一项任务遇到了一些困难!你们这里的人似乎对所有事情都有答案,所以我知道你们可以提供帮助!
这项任务是为某些形状(矩形和三角形)创建规范,但必须按原样实现:
所有形状必须实现计算界面,计算其面积/周长。 shapemanger类将计算出的形状存储在一个能够存储多达10个对象的数组中......
public class App
{
public static void main(String[] args)
{
ShapeManager sm = new ShapeManager();
Rectangle r1 = new Rectangle(100,120,10,13);
sm.addShape(r1);
sm.dump();
}
}
public interface Calculated
{
public double calculateArea();
public double calculatePerimeter();
public void dump();
}
public class Rectangle implements Calculated
{
private int xCoord, yCoord, length, width, rectangleArea, rectanglePerimeter;
public Calculated rectangleShape;
public Rectangle(int XCoord, int YCoord, int Length, int Width)
{
XCoord = xCoord;
YCoord = yCoord;
Length = length;
Width = width;
}
public double calculateArea()
{
rectangleArea = length * width;
return rectangleArea;
}
public double calculatePerimeter()
{
rectanglePerimeter = (length *2) + (width * 2);
return rectanglePerimeter;
}
public void dump()
{
System.out.println("The Area of the rectangle = " + rectangleArea);
System.out.println("The Perimeter of the rectangle =" + rectanglePerimeter);
}
}
public class ShapeManager
{
private Calculated[] calcArray;
private Calculated rectangle;
public Calculated shape;
public ShapeManager()
{
calcArray = new Calculated[10];
}
public void addShape(Calculated s)
{
int address = 0;
while (calcArray[address] != null)
{
address++;
}
calcArray[address] = s;
}
public void dump()
{
for (int x = 0; x <= 9; x++)
{
if (calcArray[x] !=null)
{
calcArray[x].dump();
}
}
}
}
目前我的输出是:
矩形区域= 0 矩形的周长= 0
我真的被困在我做错了什么,以及为什么输出没有正确计算。非常感谢您对此的任何帮助,非常感谢您的帮助和耐心!
Allyso
答案 0 :(得分:3)
将dump
方法更改为:
public void dump()
{
System.out.println("The Area of the rectangle = " + calculateArea());
System.out.println("The Perimeter of the rectangle =" + calculatePerimeter());
}
您可以通过删除以下两个字段来进一步改进:rectangleArea
和rectanglePerimeter
并使计算函数如下:
public double calculateArea()
{
return length * width;
}
现在你也节省了一些内存。然后,我会将方法重命名为getArea
和getPerimeter
。
答案 1 :(得分:2)
你的设计需要修剪一些糟糕的设计选择,比如缓存区域等:
public interface Shape {
public double getArea();
public double getPerimeter();
public void dump();
}
public class Rectangle implements Shape {
private int xCoord, yCoord, length, width;
public Rectangle(int XCoord, int YCoord, int Length, int Width) {
XCoord = xCoord;
YCoord = yCoord;
Length = length;
Width = width;
}
public double getArea() {
return length * width;
}
public double getPerimeter() {
return (length + width) * 2;
}
public void dump() {
System.out.println("The Area of the rectangle = " + getArea());
System.out.println("The Perimeter of the rectangle =" + getPerimeter());
}
}
答案 2 :(得分:0)
将'Rectangle'类中的函数'dump'替换为如下:
public void dump()
{
this.calculateArea();
this.calculatePerimeter();
System.out.println("The Area of the rectangle = " + rectangleArea);
System.out.println("The Perimeter of the rectangle =" + rectanglePerimeter);
}
您也可以在ShapeManager中的'dump'函数内的循环中执行此操作。