gpt4 book ai didi

java - 创建形状并在控制台上显示它们的程序

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:07:58 25 4
gpt4 key购买 nike

我被分配了如下的小任务。你能解释一下如何实现这个吗

Write a simple structured program and simple oo program that implements display shape function. Your program should simply print out (to console ) the number if shapes and then ask each shape to display itself which will also cause a line of output to be generated to the console , one for each shape . It is perfectly OK for your main program to create a collection of shapes before on to sorting that collection and displaying the shapes. Your program should support circles , triangles and squares but should use polymorphism so that the main program doesn't know the type of shape it is dealing with but instead treats shapes uniformly

我已经创建了一个程序来创建如下所示的形状,但我不确定如何创建所提到的形状并将它们存储在集合中并迭代以在控制台上显示这些形状。我被告知不要使用数据库来存储形状

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JApplet;

public class DrawShapes extends JApplet {

public void paint(Graphics g) {
g.setColor(Color.RED);
// drawing string
g.drawString("Hello World!", 100, 100);
// drawing rectangle
g.draw3DRect(120, 120, 120, 120, true);
g.setColor(Color.blue);
g.fill3DRect(120, 120, 120, 120, true);
// drawing circle
g.drawOval(240, 240, 120, 120);
g.setColor(Color.CYAN);
g.fillOval(240, 240, 120, 120);
// drawing square
g.drawRect(350, 350, 250, 100);
g.setColor(Color.magenta);
g.fillRect(350, 350, 250, 100);
// drawing trinale
}
}

最佳答案

只是一个想法如何去做。请注意,绘图在形状集合中是隐藏的。

interface Drawable {
public void draw(Graphics g);
}

class DrawableSquare implements Drawable{
public DrawableSquare(int x, int y, int width) { ... }
public void draw(Graphics g)
{
g.fillRect(x, y, width, width);
}
}

class Screen {
Collection<Drawable> drawables;

public void paint(Graphics g) {
for (Drawable dr: drawables) {
dr.draw(g);
}
}
}

关于java - 创建形状并在控制台上显示它们的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18657121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com