Yes, these two statements:
int radius = (width/10)/2; // the diameter is width/10 int Y = height/2 - radius; // the top edge of the squares
keep computing the same thing over and over.
There is no need to compute radius
for each iteration of the loop.
It will be "15" each time.
The same for Y
, the top edge of the squares.
It is always the same.
These two statments can be moved outside of the loop,
as in the following version of the applet,
and it will do exactly the same thing.
import java.applet.Applet; import java.awt.*; // Assume that the drawing area is 300 by 150. // Draw ten red circles side-by-side across the drawing area. public class tenCircles extends Applet { final int width = 300, height = 150; public void paint ( Graphics gr ) { gr.setColor( Color.red ); int radius = (width/10)/2; // the diameter is width/10 int Y = height/2 - radius; // the top edge of the squares int count = 0 ; while ( count < 10 ) { int X = count*(width/10); // the left edge of each of 10 // squares across the area gr.drawOval( X, Y, 2*radius, 2*radius ); count = count + 1; } } }
This version is somewhat better than the previous version because needless computations are avoided. If the loop iterated millions of times (not unusual in larger programs) moving some statements outside the loop might make the program run faster.