刻意编程D6

练习内容

  • 下雪代码练习5遍

感想

  • 抄5遍默写出错
  • 没有意识用构造函数初始化变量参数
    //构造方法  
        public MyPanel(){
            for(int i = 0 ; i < 300 ; i ++){
                x[i] = (int)(Math.random()*1024) ;
                y[i] = (int)(Math.random()*768) ;
            }
        }
  • 数组定义不熟练
    int x[] = new int[300];
    int y[] = new int[300];

附件

import java.awt.*;
public class MySnow {
    public static void main(String args[]) {
        Frame w = new Frame();
        w.setSize(1024,768);
        w.setBackground(Color.BLACK);
        
        MyPanel mp = new MyPanel();
        
        Thread t = new Thread(mp);
        t.start();
        
        w.add(mp);
        w.show();
    }
}

class MyPanel extends Panel implements Runnable{
    //int x[300] = 0;
    //int y[300] = 0;
    
    int x[] = new int[300];
    int y[] = new int[300];
    
    //构造方法  
        public MyPanel(){
            for(int i = 0 ; i < 300 ; i ++){
                x[i] = (int)(Math.random()*1024) ;
                y[i] = (int)(Math.random()*768) ;
            }
        }

    
    public void paint(Graphics g) {
        g.setColor(Color.WHITE) ;
        for (int i = 0; i < 300; i++) {
            g.drawString("*", x[i] , y[i]) ;
        }
    }
    
    public void run() {
        while(true) {
            for (int i = 0;i < 300; i++) {
            y[i]++;
            if (y[i] > 750) {
                y[i] = 0;
            }
            }
            try {
                Thread.sleep(30);
            }catch(Exception e) {}
            repaint();
        }
    }
    
}

你可能感兴趣的:(刻意编程D6)