Stanford CS106A Assignment 2 Target Solution

This Target problem is pretty fun, and is great for understanding the basics of Java that were covered in the last few lectures. Here is the problem:

Here is my solution, which you can also find on github.

The Target consists of three circles of different radiuses. The hardest part of this problem is figuring out how to get the circles to display in the center of the window. Keep in mind that when you’re drawing a circle, the circle is drawn inside a square, where the starting coordinates are in the top left corner, so you have to move over your starting point by half a radius to center the circle.

<pre>/*
 * File: Target.java
 * Name: 
 * Section Leader: 
 * -----------------
 * This file is the starter file for the Target problem.
 */

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

public class Target extends GraphicsProgram {	
	public void run() {
		putOuterCircle();
		putMiddleCircle();
		putInnerCircle();
	}
	private void putOuterCircle() {
		int radius = 72;
		int x = getWidth()/2 - radius/2;
		int y = getHeight()/2 - radius/2;
		GOval OuterCircle = new GOval (x, y, radius, radius);
		OuterCircle.setColor(Color.RED);
		OuterCircle.setFilled(true);
		OuterCircle.setFillColor(Color.RED);
		add(OuterCircle);
	}
	private void putMiddleCircle() {
		double radius = 72*64/100;
		double x = getWidth()/2 - radius/2;
		double y = getHeight()/2 - radius/2;
		GOval MiddleCircle = new GOval (x, y, radius, radius);
		MiddleCircle.setColor(Color.WHITE);
		MiddleCircle.setFilled(true);
		MiddleCircle.setFillColor(Color.WHITE);
		add(MiddleCircle);
	}
	private void putInnerCircle() {
		double radius = 72*3/10;
		double x = getWidth()/2 - radius/2;
		double y = getHeight()/2 - radius/2;
		GOval InnerCircle = new GOval (x, y, radius, radius);
		InnerCircle.setColor(Color.RED);
		InnerCircle.setFilled(true);
		InnerCircle.setFillColor(Color.RED);
		add(InnerCircle);
	}
}</pre>

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.