Shifting Circles

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
Historical topic: Java appletsModern web browsers do not run Java applets. The Applet API was deprecated for removal before Java 25 and was removed in Java 26. Treat applet examples on this page as historical object-oriented/GUI examples; for new desktop interfaces use Swing where appropriate or JavaFX/OpenJFX.

Answer:

Half the distance that separates the circles.

Shifting Circles

The left edge of the leftmost circle is 0 pixels from the left edge. The right edge of the rightmost circle is 30 - diameter. pixels from the edge. If every circle was shifted over half this distance, the drawing would be fixed. This can be done, by adding yet more arithmetic to the applet:

import javax.swing.JApplet;
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 TenShiftedCircles extends JApplet
{
  final int width = 300, height = 150;

  public void paint ( Graphics gr )
  { 
    gr.setColor( Color.red );
    int diameter = 20;
    int Y = height/2 - diameter/2;      // the top edge of the squares
    int shift = (width/10-diameter)/2;  // shift circles right

    int count =  0 ;
    while (  count < 10  )
    {
      int X = count*width/10+shift;          // the left edge of each square
      gr.drawOval( X, Y, diameter, diameter );
      count = count + 1; 
    }
  }
}

Here is what it outputs:

Embedded Java applet removed: modern browsers do not support Java applets. The surrounding source code is retained for historical study.

The arithmetic used in drawing these circles is getting somewhat messy. It is not, for example, very clear what the statement

int shift = (width/10-diameter)/2;  // shift circles right

does, even after it has been explained.

QUESTION 17:

What general technique could be used to make the program more easily understood? (This is a thought question that may take some time to answer. Hint: what type of language is Java?)