-1
public class BouncingBalls
{
public static void main(String[] args)
{    
  double[] balls = new double [10];
  double[] x = new double[1];
  double[] y = new double[1];
  double[] xspeed = new double[1];
  double[] yspeed= new double[1];

  for(int i = 0; i < 10; i++)
  {
     x[i] = 0.5;
     y[i] = 0.5;

     double r = 0.05;

     xspeed[i] = Math.random() / (5 * 24);
     yspeed[i] = Math.random() / (5 * 24);

     while(true)
     {
        StdDraw.clear();
        StdDraw.circle(x[i],y[i],r);
        x[i] = x[i] + xspeed[i];
        y[i] = y[i] + yspeed[i];

        if (x[i] > 1 || x[i] < 0)
           xspeed[i] = xspeed[i] * -1;

        if (y[i] > 1 || y[i] < 0)
           yspeed[i] = yspeed[i] * -1;

        StdDraw.show(1000/ 24);
     }          
     }     
    }
 }

我需要在屏幕上打印 10 个弹跳球,我不知道我做错了什么,它不会打印所有 10 个。我不知道如何使用任何导入方法或类似的东西。所以如果有人可以帮助我,那就太好了!!!

4

2 回答 2

1

您的绘图循环在您的 for 循环内。通常在动画中,您的绘制循环应该是最外层的循环。

public class BouncingBalls
{
    public static void main(String[] args)
    {    
        int balls = 10;
        double[] x = new double[balls];
        double[] y = new double[balls];
        double[] xspeed = new double[balls];
        double[] yspeed= new double[balls];

        double r = 0.05;

        /* initialize balls */
        for(int i = 0; i < balls; i++)
        {
            x[i] = 0.5;
            y[i] = 0.5;

            xspeed[i] = Math.random() / (5 * 24);
            yspeed[i] = Math.random() / (5 * 24);
        }

        /* draw loop */
        while(true)
        {
            StdDraw.clear();
            for(int i = 0; i < balls; i++)
            {
                /* Draw and update a ball */
                StdDraw.circle(x[i],y[i],r);
                x[i] = x[i] + xspeed[i];
                y[i] = y[i] + yspeed[i];

                if (x[i] > 1 || x[i] < 0)
                    xspeed[i] = xspeed[i] * -1;

                if (y[i] > 1 || y[i] < 0)
                    yspeed[i] = yspeed[i] * -1;
            }          
            StdDraw.show(1000/ 24);
        }     
    }
}
于 2013-11-06T03:19:24.733 回答
0

您可以从更改您的 while(true) 循环开始,该循环永远不会终止。

于 2013-11-06T02:44:20.967 回答