我编写了一个程序,可以在屏幕周围弹起一个球。下面编写的程序不起作用(球刚移出屏幕)。

但是,如果我在while循环中声明布尔变量atHorizo​​ntalEdge和atVerticalEdge,它似乎可以工作。为什么会这样?由于布尔值是为整个run()方法定义的,即使它在while循环之外,它是否也可以由while循环调用?

import acm.program.*;
import acm.graphics.*;
import java.awt.*;

public class BouncingBallv3 extends GraphicsProgram {
    public void run() {

        double x = (getWidth() - BALL_SIZE)/2 ;  //sets the starting position of ball at center
        double y = (getHeight() - BALL_SIZE)/2 ;


        GOval ball = new GOval (x, y, BALL_SIZE, BALL_SIZE ); // creates a red ball at center of screen
        ball.setFilled(true);
        ball.setColor(Color.red);
        add (ball);

        double dx = 1; //increments by which the ball moves
        double dy = 1;

        //declares boolean variables to test if ball position is at an edge
        boolean atHorizontalEdge =  (ball.getX() == getWidth() - BALL_SIZE) || ball.getX() == 0 ;
        boolean atVerticalEdge = (ball.getY() == getHeight() - BALL_SIZE) || ball.getY() == 0 ;

        /* while loop keeps the ball moving in direction dx,dy
         * if ball reaches a position at any edge, the direction dx or dy changes
         */

        while (true) {

            if (atHorizontalEdge) {          //changes direction of ball if it hits a left/right wall
                dx = -dx;
            } else if (atVerticalEdge) {     //changes direction of ball if it hits a top/bottom wall
                dy = -dy;
            }
                ball.move(dx,dy);
                pause (PAUSE_TIME);

        }



    }



    private static final double BALL_SIZE = 50;
    private static final int PAUSE_TIME = 5;
}

最佳答案

问题不在于布尔值的声明在while循环之外。这是您在while循环之外检查边界。因此,您的条件永远不会更新,它只会检查球的原始状态。

关于java - boolean 标志未在while循环中读取(java),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8025599/

10-12 18:11