递归是什么?在说此之前,我先讲个故事吧,话说从前有座山,山上有个庙,庙里有个老和尚,老和尚在讲从前有座山,山上有个庙,庙里有个老和尚,老和尚在讲从前...............这就是递归,在自己的方法里不断的调用自己。那我们怎么实现这个递归呢?
首先,我们要声明老和尚这个对象
然后,写出讲故事这个方法
最后在这个方法中调用讲故事这个方法来使老和尚不停讲故事就行了!
上例只是简单地比喻,现在我们一起用递归方法做一个漂亮的图形吧!
首先做个画板
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Border extends JFrame {
public static void main(String[] args) {
Border bd=new Border();
bd.initUI();
}
public void initUI(){
this.setBackground(Color.black);
this.setSize(800,800);
this.setDefaultCloseOperation(3);
this.setLayout(new FlowLayout());
JButton jb=new JButton("Draw");
this.add(jb);
this.setVisible(true);
Graphics g=this.getGraphics();
Draw dr= new Draw(g,(JFrame)this);
jb.addActionListener(dr);
}
}
然后实现画图:
package Sameple0402;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
public class Draw implements ActionListener {
private Graphics g;
private JFrame jf;
private int x1,y1,x2,y2,x3,y3;
public Draw(Graphics g,JFrame jf){
this.g=g;
this.jf=jf;
}
public void actionPerformed(ActionEvent e) {
String str= e.getActionCommand();
if(str.equals("Draw")){
//画出外面不变的大三角形
x1=200;
y1=200;
x2 = x1 + 500;
y2 = y1;
x3 = (int) (x1 + (x2 - x1) / 2);
y3 = (int) (y1 + (x2 - x1) * Math.sqrt(3) / 2);
g.drawLine(x1, y1, x2, y2);
g.drawLine(x1, y1, x3, y3);
g.drawLine(x2, y2, x3, y3);
DrawArc(x1,y1,x2,y2,x3,y3);
}
}
写出画出内部三角形的方法:
public void DrawArc(int x1,int y1,int x2,int y2,int x3,int y3){
//定义出结束循环的条件
if((x2-x1)<30) return ;
int a1 = (x2 +x1) / 2;
int b1 = y1;
int a2 = (x3 + x1) / 2;
int b2=(y1+y3)/2;
int a3=(x2+x3)/2;
int b3=(y2+y3)/2;
g.drawLine(a1, b1, a2, b2);
g.drawLine(a1, b1, a3, b3);
g.drawLine(a2, b2, a3, b3);
//在方法内部调用自己的方法以实现循环
DrawArc(x1,y1,a1,b1,a2,b2);
DrawArc(a1,b1,x2,y2,a3,b3);
DrawArc(a2,b2,a3,b3,x3,y3);
}
}
总结:以不变应万变
递归思想总的来说,就是传参和确定你所递归的方法。