7. แถวลำดับ

The Camtasia Studio video content presented here requires JavaScript to be enabled and the latest version of the Macromedia Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

 
รหัสที่ 7-2  โปรแกรมแสดงลูกบอล 50 ลูกเคลื่อนที่ไปมาในวินโดว์
import jlab.graphics.DWindow;
public class BouncingBalls {
  public static void main(String[] args) {
    DWindow w = new DWindow(200, 200);
    int n = 50;
    double[] x = new double[n], y = new double[n];
    double[] dx = new double[n],dy = new double[n];
    for (int i = 0; i < n; i++) {
      x[i] = 100; dx[i] = random(-5, 5);
      y[i] = 100; dy[i] = random(-5, 5);
    }
    w.setRepaintDuringSleep(true); //ให้ w แสดงภาพเมื่อ sleep เท่านั้น 
    while (true) {
      w.clearBackground();
      for (int i = 0; i < n; i++) {
        x[i] += dx[i];  
        y[i] += dy[i];
        if (x[i] <= 5 || x[i] >= 195) dx[i] = -dx[i]; //ชนผนังกลับทิศ 
        if (y[i] <= 5 || y[i] >= 195) dy[i] = -dy[i]; //ชนผนังกลับทิศ 
                x[i] = Math.min(Math.max(x[i], 5), 195);   //ปรับให้อยู่ในวินโดว์ 
                y[i] = Math.min(Math.max(y[i], 5), 195);   //ปรับให้อยู่ในวินโดว์ 
        w.fillEllipse(w.BLACK, x[i], y[i], 10, 10);
      }
      w.sleep(50);
    }
  }
  private static double random(double a, double b) {  
    return a + (b - a) * Math.random();
  }
}
©2009 S.Prasitjutrakul