如何摆脱方法中的复制粘贴代码

时间:2014-09-19 04:09:17

标签: java

我正在使用gpdraw和pen.drawOval(num1,num2)创建一个球体的直观表示,其中num1和num2的增量运算符为5.我创建它的方式让我复制粘贴相同的2代码行40次。无论如何,这似乎没有效率或专业。如何重复这些行的确切次数或重复该方法的确切次数?

DrawSphereTester类

public class SphereDrawTester
{
public static void main(String[] args)
    {
        SphereDraw draw = new SphereDraw();
        draw.draw();
    }
}

DrawSphere类

import gpdraw.*;

public class SphereDraw
{
    //Instance variables
    public SketchPad Paper;
    public DrawingTool pen;

//Constructor
public SphereDraw()
{

    Paper = new SketchPad(800, 800);
    pen = new DrawingTool(Paper);
}

public void draw()
{
    int num1 = 0;
    int num2 = 200;

    pen.drawCircle(100);

    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);
    num1 += 5;
    pen.drawOval(num1,num2);

}
}

1 个答案:

答案 0 :(得分:2)

我的朋友,是时候学习循环了!

for (int i = 0; i < 40; ++i) {
    pen.drawOval(num1,num2);
    num1 += 5;
}