Page 3 of 6 FirstFirst 12345 ... LastLast
Results 41 to 60 of 117
  1. #41
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Quote Originally Posted by Learning Java View Post
    Subtract the radius (in pixels) from x and y?
    From centerX and centerY, but yeah, you got it. So now put that into a method.

    -Gary-

  2. #42
    Learning Java is offline Senior Member
    Join Date
    May 2010
    Location
    London
    Posts
    106
    Rep Power
    0

    Default

    Thanks Gary! I'll have a go at fixing things up after dinner! :)

  3. #43
    Learning Java is offline Senior Member
    Join Date
    May 2010
    Location
    London
    Posts
    106
    Rep Power
    0

    Default

    How does this look? :)

    Java Code:
    /*
     * 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 {
    	
    	private static final double PIXELS_PER_INCH = 72;
    	
    	public void run() {
    		
    		double screenCenterX = getWidth() / 2;
    		double screenCenterY = getHeight() / 2;
    		
    		drawCircle(screenCenterX, screenCenterY, inchesToPixels(1.0), Color.RED);
    		drawCircle(screenCenterX, screenCenterY, inchesToPixels(0.65), Color.WHITE);
    		drawCircle(screenCenterX, screenCenterY, inchesToPixels(0.3), Color.RED);
    		
    	}
    	
    	public void drawCircle(double centerX, double centerY, double radius, Color c) {
    		
    		double circleWidth = radius * 2;
    		double circleHeight = radius * 2;
    		double circleX = centerX - radius;
    		double circleY = centerY - radius;
    		
    		GOval circle = new GOval (circleX, circleY, circleWidth, circleHeight);
    	
    		circle.setColor(c);
    		
    		circle.setFilled(true);
    		
    		add(circle);
    			
    	}
    	
    	public double inchesToPixels(double inches) {
    		
    		return inches * PIXELS_PER_INCH;		
    		
    	}
    	
    }

  4. #44
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Looks great!

    For the benefit of any lurkers who might be curious, you could leave out the circleHeight variable and do this:
    Java Code:
    		GOval circle = new GOval (circleX, circleY, circleWidth, circleWidth);
    But what you have is arguably clearer, and choosing clarity over efficiency is generally good policy (unless it's a big difference in efficiency, and this isn't). You might consider:
    Java Code:
    		double circleHeight = circleWidth;
    which keeps the clarity while avoiding the second multiplication and reinforcing the fact that width and height are equivalent.

    Nice job! Is it making more sense to you now?

    -Gary-

  5. #45
    Learning Java is offline Senior Member
    Join Date
    May 2010
    Location
    London
    Posts
    106
    Rep Power
    0

    Default

    Thanks!

    Yes it's all starting to make some sense now; although admittedly I do think I need some more practice, which hopefully trying to do the next exercise on my own will help with!

    Is it ok with you if I post up my code for you to check once I'm finished?

    I really appreciate the help you've given by the way.

  6. #46
    Learning Java is offline Senior Member
    Join Date
    May 2010
    Location
    London
    Posts
    106
    Rep Power
    0

    Default

    Ok this is what I have so far... I did get further but I got annoyed and started all over again. I'm guessing it's wrong anyway :(

    Java Code:
    /*
     * File: ProgramHierarchy.java
     * Name: 
     * Section Leader: 
     * ---------------------------
     * This file is the starter file for the ProgramHierarchy problem.
     */
    
    import acm.graphics.*;
    import acm.program.*;
    import java.awt.*;
    
    public class ProgramHierarchy extends GraphicsProgram {
    	
    	public static final double boxWidth = 122;
    	public static final double boxHeight = 41;
    	public static final double pixelsBetweenBottomBoxes = 21;
    	public static final double pixelsBetweenTopAndBototomBoxes = boxHeight * 2;
    
    	public void run() {
    		
    		double screenCenterX = getWidth() / 2;
    		double screenCenterY = getHeight() / 2;
    		
    		drawProgramHierarchy(screenCenterX, screenCenterY - pixelsBetweenTopAndBototomBoxes, boxWidth, boxHeight); 		// Box One
    		
    		drawProgramHierarchy(screenCenterX - pixelsBetweenBottomBoxes - boxWidth, screenCenterY, boxWidth, boxHeight);	// Box Two
    		
    		drawProgramHierarchy(screenCenterX, screenCenterY, boxWidth, boxHeight);										// Box Three
    		
    		drawProgramHierarchy(screenCenterX + pixelsBetweenBottomBoxes + boxWidth, screenCenterY, boxWidth, boxHeight);	// Box Four
    	}
    	
    	public void drawProgramHierarchy(double screenCenterX, double screenCenterY, double boxWidth, double boxHeight){
    		
    		screenCenterX -= boxWidth / 2;
    		screenCenterY -= boxHeight / 2;
    		
    		GRect box = new GRect (screenCenterX, screenCenterY, boxWidth, boxHeight);
    		add(box);		
    		
    	}
    	
    }

  7. #47
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    At some point soon, you should take a short break from the CS106A exercises and take a look at Mark Dexter's tutorials.

    Eclipse And Java Video Tutorials

    Start with Eclipse and Java for Total Beginners, even though you're not a total beginner anymore. It's 16 short video presentations, and it covers quite a bit, and will give you a much better understanding of Eclipse, Java, object-oriented programming, and even test-driven development.

    -Gary-

  8. #48
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Quote Originally Posted by Learning Java View Post
    Ok this is what I have so far... I did get further but I got annoyed and started all over again. I'm guessing it's wrong anyway :(

    Java Code:
    /*
     * File: ProgramHierarchy.java
     * Name: 
     * Section Leader: 
     * ---------------------------
     * This file is the starter file for the ProgramHierarchy problem.
     */
    
    import acm.graphics.*;
    import acm.program.*;
    import java.awt.*;
    
    public class ProgramHierarchy extends GraphicsProgram {
    	
    	public static final double boxWidth = 122;
    	public static final double boxHeight = 41;
    	public static final double pixelsBetweenBottomBoxes = 21;
    	public static final double pixelsBetweenTopAndBototomBoxes = boxHeight * 2;
    Style point: write your constants in all caps -- BOX_WIDTH instead of boxWidth. The idea is that when you see it in your code, you immediately know it's a constant and not a variable. Philosophically, constants are constants because something in the outside world says they are.
    Quote Originally Posted by Learning Java View Post
    Java Code:
    	public void run() {
    		
    		double screenCenterX = getWidth() / 2;
    		double screenCenterY = getHeight() / 2;
    		
    		drawProgramHierarchy(screenCenterX, screenCenterY - pixelsBetweenTopAndBototomBoxes, boxWidth, boxHeight); 		// Box One
    		
    		drawProgramHierarchy(screenCenterX - pixelsBetweenBottomBoxes - boxWidth, screenCenterY, boxWidth, boxHeight);	// Box Two
    		
    		drawProgramHierarchy(screenCenterX, screenCenterY, boxWidth, boxHeight);										// Box Three
    		
    		drawProgramHierarchy(screenCenterX + pixelsBetweenBottomBoxes + boxWidth, screenCenterY, boxWidth, boxHeight);	// Box Four
    	}
    	
    	public void drawProgramHierarchy(double screenCenterX, double screenCenterY, double boxWidth, double boxHeight){
    		
    		screenCenterX -= boxWidth / 2;
    		screenCenterY -= boxHeight / 2;
    		
    		GRect box = new GRect (screenCenterX, screenCenterY, boxWidth, boxHeight);
    		add(box);		
    		
    	}
    	
    }
    Yeah, it looks like you're "fighting the last war" here a bit. Try writing pseudo code for this. That means imagine yourself doing what you need to do with pencil and paper, and briefly write out each step. Something like this:

    Java Code:
            turn on griddle
            set griddle to medium
            for each sandiwch
                    butter two slices of bread
                    unwrap two slices of cheese
                    cut one slice of onion
            for each sandwich
                    put first slice of bread on griddle, butter side down
                    put two slices of cheese on top of bread
                    put one slice of onion on top of cheese
                    put other slice of bread on top of onion, butter side up
            wait four minutes
            for each sandwich
                    flip sandwich
            wait four minutes
            turn off griddle
            for each sandwich
                    remove sandwich from griddle
                    place sandwich on plate
                    slice sandwich diagonally
                    garnish with chips and pickle
    Obviously, that's a different exercise, and a longer and more complicated one, but that's the sort of style you want -- terse but complete descriptions of each step. Once you have your pseudocode, you will know what methods you need to write. I think you'll discover, for example, that if you were doing this exercise with pencil and paper, you would not start by finding the center point of the paper.

    -Gary-

  9. #49
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Also...
    Quote Originally Posted by Learning Java View Post
    Java Code:
    	public void drawProgramHierarchy(double screenCenterX, double screenCenterY, double boxWidth, double boxHeight){
    		
    		screenCenterX -= boxWidth / 2;
    		screenCenterY -= boxHeight / 2;
    		
    		GRect box = new GRect (screenCenterX, screenCenterY, boxWidth, boxHeight);
    		add(box);		
    		
    	}
    	
    }
    Parameter names are important. In this method, you're definitely not talking about the center of the screen anymore, so screenCenterX and screenCenterY are not appropriate names. You could change them to boxCenterX and boxCenterY as parameter names, but if you do that (and do you really want to deal with boxes by their center points?), then this
    Java Code:
    [COLOR="Red"]
    		boxCenterX -= boxWidth / 2;
    		boxCenterY -= boxHeight / 2;
    
    		GRect box = new GRect (boxCenterX, boxCenterY, boxWidth, boxHeight);
    [/COLOR]
    would not be appropriate, because you're not talking about the box's center anymore. This would be better:
    Java Code:
    [COLOR="Blue"]
    		double x = boxCenterX - boxWidth / 2;
    		double y = boxCenterY - boxHeight / 2;
    
    		GRect box = new GRect (x, y, boxWidth, boxHeight);
    [/COLOR]
    But again, that assumes you want to deal with boxes by their center points, and I'm not sure you do.

    -Gary-

  10. #50
    Learning Java is offline Senior Member
    Join Date
    May 2010
    Location
    London
    Posts
    106
    Rep Power
    0

    Default

    I'll start over again tomorrow and see if I can get it right. Think it would help if I went through those tutorials first?

    Thanks

  11. #51
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    What I found is key to learning programming, is learning how to think. How to break down problems, determining the steps you need to take, the resources you would need to acomplish something. Learning about the intricacies of a language comes second to the proper frame of mind. Sure, after that, finding the best solution to a given problem using language specific constructs goes hand in hand with that. For example, hmm, I'd like a growable array, so I don't have to worry about the number of elements I'm adding. Oh, lookie here, Vector! :D
    So, my recomendation would be to try and solve as many problems as you can think of or find, and then compare your solution to one made by someone with a lot of experience, see what steps they took that are different than yours, why did they solve the problem from a different viewpoint etc. One short exercise I'd reccomend would be String reversal, first made iteratively, then recursively. It shouldn't take more than 30 minutes to make both, and gives you a good grasp on the basics of different algorithms.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  12. #52
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,571
    Blog Entries
    7
    Rep Power
    21

    Default

    [QUOTE=gcalvin;119796]This would be better:
    Java Code:
    [COLOR="Blue"]
    		double x = boxCenterX - boxWidth / 2;
    		double y = boxCenterY - boxHeight / 2;
    
    		GRect box = new GRect (x, y, boxWidth, boxHeight);
    [/COLOR]
    Personally I'm not fond of side effects, whether they're local or not; I prefer an (imho more simple) approach:


    Java Code:
    GRect box = new GRect (boxCenterX - boxWidth / 2, boxCenterY - boxHeight / 2, boxWidth, boxHeight);
    ... but then again, this is all moot in Java.

    kind regards,

    Jos

  13. #53
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Default practise practise practise and post when stuck ;)

    Quote Originally Posted by Learning Java View Post
    I do doubt whether I would have been able to do so without your guidance.
    Even now looking at the code I find it hard to follow what's going on.
    yes I know that feeling

    Quote Originally Posted by Learning Java View Post
    You broke it up into 4 different methods in advance; I wouldn't have been able to think that far ahead and work that out.

    I just don't feel as if my mind is thinking about solving tasks the way it should be - does that make sense? I think my approach is wrong.
    yep that sounds like me not so long ago!!

    the first steps are always the most challenging steps. AND the ones where good guidance are most important. luckily you will get good guidance in this forum.
    I had almost identical issues when i began the cs106a course a few months ago. particularly that first stumbling block of getting your head round the need for methods... just take a look at this mess
    for loops, GLines and a bothersome expression

    recognise it??

    I got a bit carried away trying over optimise the code for the heirarchy program.. trying to make it work with any number of levels and sub levels.

    but the point is that more you practise the more it makes sense.. when(like me) your first starting out you spend what seems to be fruitless hours trying to solve simple problems. but that it just the learning curve.

    i think Karel exercises are very good to introducing the whole idea of method. you dont perhaps appreciate it their value on the first visit.
    After I had completed assignment two i did revisit the checkerboard problem in assignment one and tried to solve it a number of different ways regardless of weather it was 8x8 or 11x3 or 1x9.
    eg try to solve it by doing one row then the next row above. moving like a snake back and forth.
    solve it by moving clockwise from the outside to the middle
    solve it by moving anticlockwise from the centre square.

    try to solve it by moving randomly!!!! which proved almost impossible with the limited java you can use in Karel. i spent a week trying to break out of an infinite loop!!!!

    eventually i determined the most efficient way to solve the problem for a square of any dimensions was to do the bottom row left to right, move up to the next row and go left to right again. it took me a good deal of experimenting to work this out.

    the hours i spent doing this didnt teach me a great deal about Java specifically.. more it opened my mind to ideas about patterns / algorithms ... learning how to think about solving the problem is probably more important than being able to instantly write the code.

    the more code you learn and the more practise you do-- the better your thinking becomes
    redoing the checker board half a dozen ways gave me confidence to experiment and explore.

    if it doesnt work.... well why doesnt it work, how else can i solve it ETC,,

    mark dexters lessons are also metioned and linked earlier in this thread and i heartily recommed them especially if you have got to the end of chap 5 in the book. its more about the nuts and bolts of eclipse and how to use eclipse than it is about programing. and is a welcome break from cs106a and will save you hours of typing..

    KEEP IT UP YOUR PROGRESSING WELL.

    Regards
    Sonny
    :p I still have my "L" plates on...... directions and explanations are far more help than blaring your Horn! :p Watching:CS106a on YouTube \Reading The Art & Science of Java by Eric S Roberts

  14. #54
    Learning Java is offline Senior Member
    Join Date
    May 2010
    Location
    London
    Posts
    106
    Rep Power
    0

    Default

    Thanks for the replies guys, I do appreciate it.

    I can't think of how I could improve my previous code. I'm starting from the center because I know that the whole thing has to be centered, so to work out where my first box should be I find the center of the canvas and remove half the width of the box to find it's x coordinate. Then to work out the x coordinates for the other boxes I just add or subtract the box width plus 21 pixels to make the space between the boxes. The space between the top and bottom box I set to the boxes height multiplied by 2 and take that away from the center, so as the height of the boxes get bigger so does the space between the two <--- is that wrong? Also, the assignment doesn't mention the number of boxes needing to allow to be changed, I don't need to worry about that do I? :confused:

  15. #55
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Quote Originally Posted by Learning Java View Post
    Thanks for the replies guys, I do appreciate it.

    I can't think of how I could improve my previous code. I'm starting from the center because I know that the whole thing has to be centered, so to work out where my first box should be I find the center of the canvas and remove half the width of the box to find it's x coordinate. Then to work out the x coordinates for the other boxes I just add or subtract the box width plus 21 pixels to make the space between the boxes. The space between the top and bottom box I set to the boxes height multiplied by 2 and take that away from the center, so as the height of the boxes get bigger so does the space between the two <--- is that wrong? Also, the assignment doesn't mention the number of boxes needing to allow to be changed, I don't need to worry about that do I? :confused:
    No, you don't need to worry about more boxes, although it might be an interesting challenge to solve. On the centering, this just seems more like the Pyramid exercise than the Target exercise to me. With the Target problem, you wanted all of the circles to be centered on the same point: the center of the screen. In this case, like in the Pyramid case, it seems to make more sense to figure out what the margins need to be. Working out from the center seems like more work than working in from the edges.

    This assignment would really make more sense using an object-oriented approach, but if I remember correctly, you haven't really been introduced to classes and objects yet in the course. Try the pseudocode approach and see what you come up with. Taking a break and going through the Mark Dexter tutorials is not a bad idea at all.

    -Gary-

  16. #56
    Learning Java is offline Senior Member
    Join Date
    May 2010
    Location
    London
    Posts
    106
    Rep Power
    0

    Default

    Using the Pseudocode approach, the first thing I would do is find the center of the canvas, because I know that the finished figure has to be centered. I honestly can't think of how else I could do this exercise. If I start drawing a box from the edge then I'm not sure where I'm going to get the coordinates for that and how that's going to have to change when the width and height of the boxes change.

  17. #57
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Quote Originally Posted by Learning Java View Post
    Using the Pseudocode approach, the first thing I would do is find the center of the canvas, because I know that the finished figure has to be centered. I honestly can't think of how else I could do this exercise. If I start drawing a box from the edge then I'm not sure where I'm going to get the coordinates for that and how that's going to have to change when the width and height of the boxes change.
    Well, the specifications say that the width and the height of the boxes are constants, though it doesn't specify what they should be (meaning you can choose whatever sizes you want). You have a single box on the top row, and a row of three boxes below it.

    Java Code:
    public class ProgramHierarchy extends GraphicsProgram {
            private static final double BOX_WIDTH = 120.0;
            private static final double BOX_HEIGHT = 50.0;
    
            private GRect drawBox(double x, double y, String text) {
                    //TODO: Write this. text needs to be centered in box
            }
    
            private void drawConnectingLine(GRect fromBox, GRect toBox) {
                    //TODO: Write this too. Line needs to go from
                    //          bottom center of fromBox to top center of toBox
            }
    
            public void run() {
                    // two rows of boxes means three empty spaces --
                    // top margin, between space, and bottom margin
                    // simplest thing is to make them all equal
                    double verticalMargin = (getHeight() - 2 * BOX_HEIGHT) / 3;
    
                    // three boxes in bottom row means four horizontal spaces
                    double horizontalMargin = (getWidth() - 3 * BOX_WIDTH) / 4;
    
                    // top box is two margins and one box over from left edge
                    double x = 2 * horizontalMargin + BOX_WIDTH;
                    double y = verticalMargin;
                    GRect box1 = drawBox(x, y, "Program");
    
                    x = horizontalMargin;
                    y += BOX_HEIGHT + verticalMargin;
                    GRect box2 = drawBox(x, y, "GraphicsProgram");
                    x += BOX_WIDTH + horizontalMargin;
                    GRect box3 = drawBox(x, y, "ConsoleProgram");
                    x += BOX_WIDTH + horizontalMargin;
                    GRect box4 = drawBox(x, y, "DialogProgram");
    
                    drawConnectingLine(box1, box2);
                    drawConnectingLine(box1, box3);
                    drawConnectingLine(box1, box4);
            }
    }
    That's not very pretty, I'll admit, but without modeling a parent/child relationship, it's the simplest thing I can think of. You could do an array, I suppose, but you've got the different Strings to assign, so you'd have to put them in an array as well, and with the top row, and just three boxes in the bottom row, it just seems simpler to me to do it this way. I didn't really mean to give away so much, but I wanted to illustrate what I meant by working from the edges. And this is by no means the only way to do it. There's still quite a bit of code to write -- choosing a font size for the text and centering it in the boxes is a bit of work. The drawConnectingLine() method should be easy enough.

    Is it clear that this code centers the boxes?

    -Gary-

  18. #58
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Thumbs up

    Quote Originally Posted by Learning Java View Post
    Thanks for the replies guys, I do appreciate it.

    Also, the assignment doesn't mention the number of boxes needing to allow to be changed, I don't need to worry about that do I? :confused:
    NO dont worry about that at all.. that was me just trying to stretch myself (and trying to do something that wasn't realistically possible given my knowledge at that time)

    just get it working with one box and then three underneath

    i added some static cobnstants when i did this exercise just to so i could keep numbers out of the actual code. something like
    Java Code:
    private static final int LEVELS = 2;
    private static final int SUBBOXES = 3;
    blast i cant find my original code for this exercise:mad:

    but i think i used for loops just like the draw pyramid exercise. to me it seemed just like an extension or progression of the pyramid exercise.
    :p I still have my "L" plates on...... directions and explanations are far more help than blaring your Horn! :p Watching:CS106a on YouTube \Reading The Art & Science of Java by Eric S Roberts

  19. #59
    Learning Java is offline Senior Member
    Join Date
    May 2010
    Location
    London
    Posts
    106
    Rep Power
    0

    Default

    I'm not getting it bro. I think I'll take a break from this all, then maybe go through some of the previous stuff and see if that helps. I just don't think the lectures I've seen up to this point have prepared me to do this exercise to be honest.

  20. #60
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Cool

    Quote Originally Posted by Learning Java View Post
    I'm not getting it bro. I think I'll take a break from this all, then maybe go through some of the previous stuff and see if that helps. I just don't think the lectures I've seen up to this point have prepared me to do this exercise to be honest.
    You are quite right. the lectures you have seen to this point have not prepared you. Remember the Standford students not only get the benefit of the lecture. they also get support from their section leader in small groups for an additional 3 hours a week. you dont get that so dont be disheartened that you can not progress as quickly as the course is set out.

    I statrted 3 months ago and am only on lecture 12. but also you will divert to other stuff to cement the things you have learned and explore other things.
    Mark Dexters tutorials are really good and easy to follow have a look at them.

    I must admit this exercise really gave me head ache because the methods thing hadn't clicked. also if your math aint too hot thats a further handicap
    but not insurmountable.

    @ MODERATOR
    forgive me Mr Moderator for spoon feeding but i dont think the guy is dumping his homework and i think if he sees the answers it might help things click into place. ill edit the post and remove the code in a few days.

    so here is a complete walk through of how i did this exercise.
    it might not be strictly correct but it will serve a purpose.
    after all i'm still a beginner myself.
    i will tackle the methods first and then the run.

    strictly speaking you wouldnt do it precisley that way you usually do a bit of code compile it see if it works then carry on
    ill use php tags the colour looks crappy but it will be easier for you to read off the screen. I suggest pasting straight into and empty class in Eclipse called Heirarchy. it will complile straight off. you can follow it through
    then delete all the comments.. perhaps you might want to print it as is
    before you delete the comments.. but any way here goes..

    PHP Code:
    import acm.graphics.GLabel;
    import acm.graphics.GLine;
    import acm.graphics.GRect;
    import acm.program.GraphicsProgram;
    
    public class Heirarchy extends GraphicsProgram {
    
    	/*
    	 * this will make the canvas 600 x 600 square it may help if you can relate
    	 * to a concrete figure rather than some notion of getWidth();
    	 */
    	private static final int APPLICATION_WIDTH = 600;
    	private static final int APPLICATION_HEIGHT = 600;
    
    	/* variables for the box dimensions */
    	private static final double BOX_WIDTH = 150;
    	private static final double BOX_HIEGHT = 80;
    
    	/*
    	 * variables for the diagram itself there are two levels & three sub-boxes
    	 * on level two
    	 */
    	private static final double LEVELS = 2;
    	private static final double SUBBOXES = 3;
    
    	/*
    	 *DRAWBOX: remember your high school math teacher always told you
    	 * to write down every step of your working out because then someone could
    	 * follow what you were doing. its kind of the same in java.
    	 * 
    	 * a GRect Object can only be drawn from its top left corner we just have to
    	 * calculate where that is - from the centre -  because we are going to pass the
    	 * coordinates of the centre to this method as centreX and centreY and then
    	 * calculate where the box top left hand corner will be in each axis
    	 * so lets do that and declare the variables (set out our calculations)
    	 * as we go along
    	 */
    	
    	/*DRAWBOX METHOD*/
    	private GRect drawBox(double centerX, double centerY) {
    		// so we declare a double topLeftX
    		// we calculate top left on the x axis using the expression
    		double topLeftX = centerX - (BOX_WIDTH / 2);
    		
    		// then we calculate top left on the y axis
    		double topLeftY = centerY - (BOX_HIEGHT / 2);
    		
    		// construct a new GRect called "box" at the locations we calculated
    		GRect box = new GRect(topLeftX, topLeftY, BOX_WIDTH, BOX_HIEGHT);
    		
    		// return "box" to where it was called from. 
    		return box; 
    	}
    
    	/* BETTER BOX METHOD: from four lines of code to one.
    	 * topLeftX & topLeftY are local variables they only exist in the
    	 * drawBox method. once the method has finished, they disappear.
    	 * this next code is simpler or more concise but it does exactly the same thing.
    	 * in Professor Mehran Sahami speak were gonna send it to the caller 
    	 * straight out of of the factory pre-constructed and ready to use (add) .
    	 * Rather than setting out our working out and declare each variable like our
    	 * math teacher taught us, Java is pretty smart so we can pass each parameter as 
    	 * a complete expression.
    	 * the GRect doesn't have a name like "box" it doesn't need one.
    	 * the caller can give it a name if it wants to or add it straight to the canvass
    	 * don't feel you have to do it this way, do it long hand till your comfortable
    	 * most times i think you do it long hand first then start to simplfy
    	 * and refine as you go along.
    	 * compare what's between the commas with the variables declared in the 
    	 * previous method...
    	 */
    	
    	private GRect betterBox(double cX, double cY) {
    		return new GRect(cX - BOX_WIDTH / 2, cY - BOX_HIEGHT / 2, BOX_WIDTH,
    				BOX_HIEGHT);
    	}
    
    	/* DRAW LABEL
    	 * the label is centred the same as the box cX, cY,
    	 * a GLabel object can only be drawn from the bottom left(not top left)
    	 * we'll calculate the x and y from Cx and Cy just like we did with box
    	 * only remembering to ADD half the ascent of the label because its being
    	 * worked out from the bottom left, not the top left..
    	 * it's Y co-ordinate will be greater than than y co-ordinate of 
    	 * box because its further down.    
    	 */
    	private GLabel drawLabel(double cX, double cY, int label) {
    		// first we define the label,, ill come back to this bit
    		// for now just notice that i'm calling another method 
    		// to define the GLabel text and im going to pass that method an integer value.
    		GLabel boxLabel = new GLabel(getMyLabel(label));
    		// to find the x co-ordinate we half the width of the label and subtract from cX
    		double labelX = cX - boxLabel.getWidth()/2;
    		// to find the y we half the ascent of the label and ADD to cY
    		double labelY = cY + boxLabel.getAscent()/2;
    		//now we can set its location
    		boxLabel.setLocation(labelX ,labelY);
    		// and return
    		return boxLabel;
    		
    	}
    	
    	/* BETTER LABEL
    	 * and here it is in a more concise form. Not quite as consise as the box method
    	 * but I wont go into exactly why. you'll figure that out in a few weeks
    	 */
    	private GLabel betterLabel(double cX, double cY, int label){
    		GLabel boxLabel = new GLabel(getMyLabel(label));
    		boxLabel.setLocation(cX - boxLabel.getWidth()/2, cY + boxLabel.getAscent()/2);
    		return boxLabel;
    		
    	}
    
    	/* so lets do the getMyLabel thing.
    	 * You haven't covered strings in any detail but for the purposes of this
    	 * exercise just think of them as another data type like ints or doubles
    	 * and we will do a series of ifs' cos its simple (although not strictly correct)
    	 * it will suffice for the intends and purposes here.
    	 * you can find out about if/else-if yourself because this is not the best
    	 * example to demonstrate it anyway.
    	 
    	 * this method will return a label as a string.
    	 * there are four labels we'll number them one to four
    	 * in the order they will be added to the canvass.
    	 */
    	private String getMyLabel(int label) {
    		// if the value passed is 1
    		if(label == 1){
    			return "Program"; 
    		}
    		if(label == 2){
    			return "Graphics Program";
    		}
    		if (label == 3){
    			return "Console Program";
    		}
    		if (label == 4){
    			return "Dialogue Program";
    		}
    		// we should not ever get to this point but a final
    		// return is needed as a default if none of the above applies.
    		// look at the braces
    		// Without this default, eclipse would ask you for a return statement
    		// and you would say "hey! but there's four of them already." it is what it is 
    		// and its something you can find out about by experiment and research.
    		return null;
    	}
    	
    	/*next we come to drawing the Glines
    	 * again let me iterate that the following may not be strictly 
    	 * correct or strictly conventional but will suffice for the 
    	 * intends and purposes of this exercise.
    	 * The tricky bit about the GLines is that whilst there's four
    	 * boxes and four labels, there's only three GLines 
    	 * but there are four points and we know the the first point
    	 * which is the bottom of the "Program" box will remain the same.
    	 * to be honest when I first spent many hours
    	 * doing this exercise I got the boxes and labels set out first before
    	 * I attempted to draw the GLines bit.
    	 * Also, i'm not suggesting that you could have written these
    	 * methods out right and then done the run method last.
    	 * you would do a bit at time compiling as you go
    	 *  see the thread ive linked below marked THREAD. for an explanation
    	 * We are not going to draw a Gline after the first box
    	 * we will only draw lines when we draw the boxes underneath.
    	 * Now you really should notice that once again we will be passing the 
    	 * the exact same variables to this method as we passed to box and 
    	 * label.  also the method takes in two parameters but we need
    	 * four parameters to construct a GLine. startX is easy. startY just
    	 * take off half box height. endX and endY are a fixed point
    	 * we could in fact declare them as constants, but as you will
    	 * see we will have a variable in the run method.
    	 * constants are better(arguably) but the variable in the run method
    	 * will serve as better explanation of how we arrived at this expression
    	 * */
    
    	private GLine drawLine(double cX, double cY){
    		double startX = cX ;
    		double startY = cY - BOX_HIEGHT / 2;
    		double endX = APPLICATION_WIDTH / 2;
    		double endY = (APPLICATION_HEIGHT / (LEVELS+1)) + BOX_HIEGHT / 2;
    		GLine myLine = new GLine (startX,startY,endX,endY);
    		return myLine;
    		
    	}
    	
    	/* A BETTER LINE
    	 * and simplified, notice i have used getWidth and getHeight this time
    	 * instead of application width and application height and i have used
    	 * extra parenthesis for the last expression to ensure that 
    	 * Java does the maths correctly, Also the last expression is on a new line
    	 * the only reason for this is to make it more readable. Again note the commas
    	 * and compare to the declarations in the previous method..  
    	 * Yep its exactly the same!
    	 */
    	
    	private GLine betterLine(double cX, double cY) {
    		return new GLine( cX, cY - BOX_HIEGHT/2, getWidth() / 2,
    				(getHeight() / (LEVELS + 1)) + BOX_HIEGHT / 2);
    	}
    	
    	/* so now im going to use two nested for loops like the pyramid
    	 * exercise only as Professor Mehran might say "a bit more funky"
    	 * 
    	 * we know there are two levels.. to centre these levels in the Yaxis
    	 * we must divide by three or (LEVELS + 1)
    	 * if you have a fence which is 10 fence panels long you 
    	 * need 11 posts to hold it up the +1 is that extra post
    	 * in the x axis the divisions will depend on how many boxes there
    	 * are in the row and this is where things get a little funky.
    	 * How do we determine the number of boxes in the next row?
    	 * We know how many there are right!  yeah but Java doesnt know
    	 * Java just knows there are 3 SUBoxes..  confused???
    	 * Okay think a little outside the box.
    	 * remember the checkboard two loops
    	 *  1st loop sets out 8 columns , 
    	 *  	2nd loop does 8 squares,
    	 *  result 8 colums with 8 bricks in each
    	 *  
    	 *  in pyramid our loops might be set out like this*/
    
    	private void pyramidLoops(){
    		int BRICKS_BASE = 14;
    		for(int i = BRICKS_BASE ; i > 0; i--){  
    			// counting down to 1  i.e "i" is reducing each time
    			for (int j = 0; j < i; j++){
    				// j is counting up to "i", because "i" is reducing each time
    				// we get one less brick on each subsequent row.
    			}
    		}
    	}
    	
    	/*
    	 *  the amount of boxes drawn in heirarchy is a little different
    	 *  and we need to determine how many boxes on the next row.
    	 *  the J loop will have to change what it counts to each time.
    	 *  and also we are going to work from the top to bottom not 
    	 *  bottom to top like pyramid. you can work out a way of going 
    	 *  bottom to top yourself.  
    	 *  so thinking outside the box, imagine there where three levels. 
    	 *  if that were so, on row 3 there would be another three boxes 
    	 *  under each of the three boxes on row two.  a total of 9
    	 *  if there were four levels there would be another 3 under 
    	 *  each of those 9..  so thats 27
    	 *  so we have one box on the first level the 0th iteration
    	 *  (zero times through or when i = 0)
    	 *  we will have three boxes on the next row (when i = 1)thats 1 * SUBBOXES
    	 *  if we were to have a third row where i = 2 there would be
    	 *  9 boxes  that is 1 * SUBBOXES * SUBOXES.
    	 *  note i = 2 and we multiplied 1 * (SUBBOXES * 2).
    	 *  time for another method. and were gonna pass this method
    	 *  the index "i" from the first for loop
    	 *  when indexI is 0 the for loop doesn't even start and we are returned 1
    	 *  when indexI is 1   1*3 is returned
    	 *  when indexI is 2   3*3 is returned
    	 *  when indexI is 3   9*3 is returned  and so on,  make sure you follow this
    	 *  and understand what is happening 
    	 */
    	
    	private int boxesInRow (int indexI) {
    		int numBoxes = 1;
    		for (int n = 0; n < indexI; n++){
    			numBoxes*=SUBBOXES;
    		}
    	return numBoxes;
    	}
    	
    	
    	/* and now we can run the two loops
    	 * ySpace is the vertical distance between the centres
    	 * boxesInRow is calculated on each iteration of the i loop
    	 * xSpace or the distance between the centres of the boxes
    	 * will also be calculated on each iteration of the  i loop 
    	 * and the j loop will count upto the number of boxesInRow*/
    	
    	public void run() {
    		int label = 1;  // this is out label counter
    		double ySpace = getHeight() / (LEVELS + 1); 
    		for(int i = 0; i < LEVELS; i++){
    			int boxesToDraw = boxesInRow(i);
    			double xSpace = getWidth()/(boxesToDraw+1);
    			for (int j = 0; j < boxesToDraw; j++) {
    				double cX = xSpace + j * xSpace; // if this is unclear reveiw the
    				double cY = ySpace + i * ySpace; // checkerboard lecture.
    				GRect box = betterBox(cX, cY); // see this
    				add(box);                     // and this two lines of code
    				
    				add(betterLabel(cX, cY, label)); // see this its the same but
    													// better only one line.
    				label++; // increase our label counter by one
    				if (i > 0) { // only draw a GLine if i is greater than 0.
    					add(betterLine(cX, cY));
    				}// if statement ends
    			}// j loop ends
    		}// i loop ends
    	}// run method ends
    
    	/*
    	 * and once again we can simplify further but ill leave that for you to play
    	 * around with notice the three things we added all took in the same
    	 * values perhaps you could write a method to add all three things.
    	 * just think carefully about what you pass the method*/
    	
    	
    }
    :p I still have my "L" plates on...... directions and explanations are far more help than blaring your Horn! :p Watching:CS106a on YouTube \Reading The Art & Science of Java by Eric S Roberts

Page 3 of 6 FirstFirst 12345 ... LastLast

Similar Threads

  1. Help for University Project
    By ja107 in forum Networking
    Replies: 3
    Last Post: 03-18-2010, 10:22 AM
  2. Help for University Project
    By ja107 in forum Networking
    Replies: 1
    Last Post: 03-04-2010, 12:22 AM
  3. University Of Nottingham Website Survey
    By MuslimCoder in forum Reviews / Advertising
    Replies: 1
    Last Post: 03-02-2009, 10:42 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •