我想得到不同的结果作为输入的数字。
例如,当我放置4时,我得到了矩形的结果,当我放置3时,我得到了三角形。
import java.util.Scanner;
public class Source9_1 {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int x, y; // 클래스 Parameter(내부 변수)
Point[] v = new Point[n]
for(int i=0; i <= v.length; i++) {
v[i] = new Point();
v[i].
}
}
class Point {
int x, y; // 클래스 Parameter (내부 변수)
public void setPoint(int x, int y) { // Point 세팅
this.x = x;
this.y = y;
}
public void printPoint() { // Point 출력
System.out.println("x = " + x + ", y = " + y);
}
}
class Rectangle extends Point {
Point[] p = new Point[4];
Rectangle(Point[] p) {
this.p = p;
}
}
class Triangle extends Point {
Point[] p = new Point[3]; // 3개의 Point인스턴스를 담을 배열 생성
Triangle(Point[] p) {
this.p = p;
}
}
class Shape extends Point { // Point 배열 및 상속을 받아 세팅 후 출력가능한 클래스
Point coord[10];
static int s = 0; // 불릴 때마다 값 증가 ???
public void printShapePoint() { // 배열에 담은 Point 출력
}
public void setShapePoint() { // 배열에 담기 위해 Point 증가
}
}
到目前为止,我已经像这样编码了,但是我现在不知道该怎么办。
输入数字后如何得到不同的结果?
答案 0 :(得分:2)
首先,关于您的Rectangle
和Triangle
类。我觉得您错过了您的意思(双关语不是故意的),因为您已经将两者都扩展了Point
类。这没有多大意义,因为您拥有Shape
类,它将作为它们的超类做得更好。
所以:
class Rectangle extends Shape {
...
}
class Triangle extends Shape {
...
}
到目前为止,您所拥有的一切:
Point
对象。下一步您需要做什么:
Point
个对象Triangle
或Rectangle
对象,具体取决于您拥有的点数。因此,在您的for
语句中,您需要执行以下操作:
for (int i=0; i <= v.length; i++) {
v[i] = new Point();
x = sc.nextInt(); // Save 'x' value into the variable
y = sc.nextInt(); // Save 'y' value into the variable
v[i].setPoint(x, y); // Set both values using the method from Point
}
然后,由于Rectangle
和Triangle
都具有Shape
作为公共超类,因此您可以将这些类之一的对象放在Shape
变量中。因此,在for
语句之后,您将要执行以下操作:
Shape s; // Create the empty variable here, so it will exist outside the if-else scope
if (n == 3)
s = new Triangle(v);
else
s = new Rectangle(v);
最后,只打印您的观点:
for (int i = 0; i < v.length; i++)
v[i].printPoint();
差不多了。
答案 1 :(得分:0)
佩德罗的答案很好。我还有其他建议。使用开关或条件开关来创建不同类型的形状有点代码味道。我建议为此使用抽象工厂。我举了一个小例子来说明如何here。
从点的数量推断形状可能不够。例如,一个矩形由两个点(而不是四个)定义,一条线也将定义,即使您当前未对线进行建模。
我认为按名称选择形状并使用工厂从输入的点实例化形状会更清楚。
请注意,他塑造对象层次结构经常用于解释对象方向。像这样设计类结构有很多陷阱。例如,请参见this article。还请记住容易被违反的Liskov替代原则,请参见this article。