编程创建形状并在控制台上显示它们 [英] Program to create shapes and show them on console

查看:156
本文介绍了编程创建形状并在控制台上显示它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了如下的小作业。你能否详细说明如何实现这个

I was given small assignment as below . Can you please throw some light on how to implement this


编写一个简单的结构化程序和简单的oo程序来实现显示形状功能。你的程序应该简单地打印(控制台)数字,如果形状,然后要求每个形状显示自己,这也将导致生成一行输出到控制台,每个形状一个。对于主程序来说,在对该集合进行排序和显示形状之前创建一组形状是完全可以的。你的程序应该支持圆形,三角形和正方形,但是应该使用多态,这样主程序就不知道它正在处理的形状类型,而是统一处理形状

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

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

I had created a program to create shapes like below but i'm not sure on how to create the shapes as mentioned and store them in collection and iterate to display these shapes on console. I was told not to use the database for storing shapes

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
    }
}


推荐答案

只是一个想法如何做到这一点。请注意,图形对形状集合是隐藏的。

Just an idea how to do it. Notice, that the drawing is hidden from the shapes collection.

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);
     }
  }
}

这篇关于编程创建形状并在控制台上显示它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆