The Art and Science of Java - Exercise Solutions - Chapter 3, Exercise 11
Can anyone help me with the Chapter - Exercise 11 Solution. This is what I have done so far. I'm wondering if there is a better way to resolve the exercise.
If you don't have the book here it is the exercise:
11. Exercise 4 in Chapter 2 asks you to write a graphics program thal produces a diagram of a simple frame house. If you wanted to make the DrawHouse program easy to change, what named constants shou ld you define to provide the necessary flexibility? Rewrite the program so that it uses these named constants rather than explicit coordinate values.
Code from Exercise 4, Chapter 2:
import acm.graphics.*; import acm.program.*; import java.awt.*;
public class JHouse extends GraphicsProgram{ public void run(){ GRect rectWalls = new GRect(((getWidth() - 300)/2), ((getHeight()-120)/2), 300, 120); GRect rectDoor = new GRect(((getWidth() - 50)/2), ((getHeight()-80)/2+20), 50, 80); GRect windLeft = new GRect(((getWidth() - 40)/2-90), ((getHeight()-40)/2), 40, 40); GRect windRight = new GRect(((getWidth() - 40)/2+90), ((getHeight()-40)/2), 40, 40); GLine roofRight = new GLine(527,177,370,50); GLine roofLeft = new GLine(228,177,369,50); GLine windFrameR = new GLine(287,255,287,216); GLine windFrameL = new GLine(467,255,467,216); GOval doorHandle = new GOval(387,255,7,7); add(rectWalls); add(rectDoor); add(windLeft); add(windRight); add(roofRight); add(roofLeft); add(windFrameR); add(windFrameL); add(doorHandle); } }
Possible Solution for Exercise 11, Chapter 3
import acm.graphics.*;
import acm.program.*;
public class JHouseRevised extends GraphicsProgram{ public void run(){ add(new GRect(((getWidth()-HOUSE_SIZE)/2),((getHeight()-HOUSE_SIZE+ROOF_SIZE)/2),HOUSE_SIZE,HOUSE_SIZE/2)); add(new GRect(((getWidth()-(DOOR_SIZE/2))/2),((getHeight()-DOOR_SIZE)/2+(DOOR_SIZE/2)),DOOR_SIZE/2,DOOR_SIZE)); add(new GRect(((getWidth()-(DOOR_SIZE/2))/2-90),((getHeight()-(DOOR_SIZE/2))/2),(DOOR_SIZE/2),(DOOR_SIZE/2))); add(new GRect(((getWidth()-(DOOR_SIZE/2))/2+90),((getHeight()-(DOOR_SIZE/2))/2),(DOOR_SIZE/2),(DOOR_SIZE/2))); add(new GLine(((getWidth()+HOUSE_SIZE)/2),((getHeight()+(ROOF_SIZE-HOUSE_SIZE))/2),(getWidth()/2),(getHeight()-(HOUSE_SIZE*2)+ROOF_SIZE))); add(new GLine(((getWidth()-HOUSE_SIZE)/2),((getHeight()+(ROOF_SIZE-HOUSE_SIZE))/2),(getWidth()/2),(getHeight()-(HOUSE_SIZE*2)+ROOF_SIZE))); add(new GLine((getWidth()/2-(HOUSE_SIZE/4)-15),((getHeight()/2)+DOOR_SIZE/4),(getWidth()/2-(HOUSE_SIZE/4)-15),((getHeight()/2)-DOOR_SIZE/4))); add(new GLine((getWidth()/2+(HOUSE_SIZE/4)+15),((getHeight()/2)-DOOR_SIZE/4),(getWidth()/2+(HOUSE_SIZE/4)+15),((getHeight()/2)+DOOR_SIZE/4))); add(new GOval(((getWidth()-DOOR_HANDLE)/2+(DOOR_SIZE/6)),(getHeight()/2+(DOOR_SIZE/2)),DOOR_HANDLE,DOOR_HANDLE)); } /*Constant*/ private static final int HOUSE_SIZE = 300; private static final int ROOF_SIZE = 200; private static final int DOOR_SIZE = 100; private static final int DOOR_HANDLE = 7; }


















