# Thread: CS106A Stanford University

1. Senior Member
Join Date
May 2010
Location
London
Posts
106
Rep Power
0
Thanks for taking the time to post that up mate! I decided to do some "funky" stuff and here's what I came up with... I know it's not correct but at least now I know how to use switch statements! hahaha.

Java Code:
```/*
* File: ProgramHierarchy.java
* Name:
* ---------------------------
* 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 BOX_WIDTH = 170;
public static final double BOX_HEIGHT = 60;
public static final double TBOX_SPACING = 70;
public static final double BBOX_SPACING = 20;

public void run() {

drawBox(1);
drawBox(2); drawLine(1);
drawBox(3); drawLine(2);
drawBox(4); drawLine(3);

}

public void drawBox (int boxNum) {

double centerX = getWidth() / 2;
double centerY = getHeight() / 2;

switch (boxNum) {

case 1:

double x = centerX - (BOX_WIDTH / 2);
double y = centerY - TBOX_SPACING - BOX_HEIGHT;

GRect box1 = new GRect (x, y, BOX_WIDTH, BOX_HEIGHT);

case 2:

x = centerX - (BOX_WIDTH / 2) - BOX_WIDTH - BBOX_SPACING;
y = centerY;

GRect box2 = new GRect (x, y, BOX_WIDTH, BOX_HEIGHT);

case 3:

x = centerX - (BOX_WIDTH / 2);
y = centerY;

GRect box3 = new GRect (x, y, BOX_WIDTH, BOX_HEIGHT);

case 4:

x = centerX - (BOX_WIDTH / 2) + BBOX_SPACING + BOX_WIDTH;
y = centerY;

GRect box4 = new GRect (x, y, BOX_WIDTH, BOX_HEIGHT);

}

}

public void drawLine (int boxNum) {

double centerX = getWidth() / 2;
double centerY = getHeight() / 2;

switch (boxNum) {

case 1:

double x = centerX;
double y = centerY - TBOX_SPACING;
double xx = centerX;
double yy = centerY;

GLine line1 = new GLine (x, y, xx, yy);

case 2:

x = centerX;
y =  centerY - TBOX_SPACING;
xx = centerX - BOX_WIDTH - BBOX_SPACING;
yy = centerY;

GLine line2 = new GLine (x, y, xx, yy);

case 3:

x = centerX;
y = centerY - TBOX_SPACING;
xx =centerX + BOX_WIDTH + BBOX_SPACING;
yy = centerY;

GLine line3 = new GLine (x, y, xx, yy);

}

}

}```
Last edited by Learning Java; 05-14-2010 at 06:57 PM.

2. Senior Member
Join Date
Mar 2010
Posts
952
Rep Power
8
Originally Posted by Learning Java
Thanks for taking the time to post that up mate! I decided to do some "funky" stuff and here's what I came up with... I know it's not correct but at least now I know how to use switch statements! hahaha.
Yeah, this doesn't look like a great idea. First of all, be careful with your indentation. Maybe this is just happening when you paste into the forum, but somehow I doubt it. You can always do Ctrl-A Ctrl-I in the Eclipse editor to fix it. Second, the idea of drawBox() and drawLine() methods is not bad, but to have those methods behave differently based on which box they're drawing (signified by an int identifier) is a bad idea -- better to just leave that logic in the calling method, even if it means scrapping drawBox() and drawLine() altogether.

Frankly, I don't see much hope for letting each box figure out on its own where it should be drawn. And since there are only four boxes, I don't think it makes much sense to spend time trying to make that work. You'd need to tell the box drawing method something so that it can figure out where its x and y need to be, and it's likely much easier to just tell it where x and y are. It's possible to draw the bottom row of boxes in a loop, but since you need to assign a unique String to each one, and again, since there are only three of them, it doesn't make much sense to do it that way.

But there's still plenty for a drawBox() method to do. It needs to create and size a GLabel, and center it within the GRect. That's enough to justify a method. I had my drawBox() return the GRect object, so that I could use it in my drawConnectingLine() call.

Unless I'm missing something in your code, your drawing will not be properly centered top-to-bottom. The top edge of your bottom row of boxes looks to be right on the center line, while the bottom edge of the top box is 70 pixels above center line. This means there will be 70 pixels more space on the bottom of the drawing than on the top.

-Gary-

3. Senior Member
Join Date
May 2010
Location
London
Posts
106
Rep Power
0
You can always do Ctrl-A Ctrl-I in the Eclipse editor to fix it.
I didn't actually know that... that's going to save me a lot of time! Thanks!

Unless I'm missing something in your code, your drawing will not be properly centered top-to-bottom. The top edge of your bottom row of boxes looks to be right on the center line, while the bottom edge of the top box is 70 pixels above center line. This means there will be 70 pixels more space on the bottom of the drawing than on the top.
I wasn't aware that it had to be centered top to bottom, and the example in the exercise wasn't centered top to bottom - I guess it's a good idea to center it all though anyway.

4. Senior Member
Join Date
May 2010
Location
London
Posts
106
Rep Power
0
Question: You see how you did:

Java Code:
`GRect box1 = drawBox(x, y, "Program");`
How does that work exactly? I didn't even know that was possible; it looks as if you're assigning an x and y coordinate for the GRect but then you're also passing a string?

The whole "GRect box1 =" is new to me, wasn't aware of it previously.

Thanks

5. Question: You see how you did:

Code:
GRect box1 = drawBox(x, y, "Program");
How does that work exactly? I didn't even know that was possible; it looks as if you're assigning an x and y coordinate for the GRect but then you're also passing a string?

The whole "GRect box1 =" is new to me, wasn't aware of it previously.
you can pass whatever variables you need to the method, you can pass it a string an int a double or even a whole other object like a GLabel.

its not the
Java Code:
```private void drawBox(int x, int y,String str){
}```
that constructs the GRect
within that method
there will be a constructor
Java Code:
`GRect box = new GRect (x,y,height,width)`
the constructor makes the GRect...

the variables in the method header are just being passed to the method

it isnt strictly always constructed like that.
you can also construct like this for a GRect
Java Code:
```GRect box = new GRect (height,width)
box.setlocation(x,y)```

the string was passed because maybee your going to do something else with the string like make a GLabel...
Last edited by sonny; 05-14-2010 at 09:56 PM. Reason: clarity code tags

6. Senior Member
Join Date
May 2010
Location
London
Posts
106
Rep Power
0
Aaaah right that makes sense now! Cheers mate! :)

7. Senior Member
Join Date
Mar 2010
Posts
952
Rep Power
8
While it's true that you call the GRect constructor to make a GRect, you can also return a GRect (or any other object) from a method. Java Object variables actually hold a reference to the object -- the object is not copied around when it is passed as a parameter, but stays where it is, and its location on the heap is passed. This might confuse you a bit, but most (nearly all) of the time it is what you expect and what you want.
Java Code:
```        GRect drawBox(double x, double y, String text) {
GRect box = new GRect(x, y, BOX_WIDTH, BOX_HEIGHT);
// TODO: add() the box to the canvas
// TODO: create GLabel, center it in box and add() it
return box;
}```
This allows you to save the GRect (again, it's really a reference to the GRect that was already created and added to the canvas) in a variable, so you can do this later:
Java Code:
`                drawConnectingLine(box1, box2);`
While it's not easy for a box to know where it should appear on the canvas, it is pretty easy for it to know where its ConnectingLine should attach.
Java Code:
```        public void drawConnectingLine(GRect fromBox, GRect toBox) {
// fromBox connecting point is bottom center
double fromX = fromBox.getX() + fromBox.getWidth() / 2;
double fromY = fromBox.getY() + fromBox.getHeight();
// TODO: compute toX and toY (top center of toBox), create and add GLine
}```
There's just enough complexity there to make putting it in a method worthwhile. Sure, you could compute those points for the GLines in your calling code, but I wager it would be more complex and confusing than this. This also gives you flexibility -- suppose you decide that the From connecting point should be 80% to the right, and the To point should be way to the left, instead of centering them both?

-Gary-

8. Originally Posted by gcalvin
Java Code:
```        GRect drawBox(double x, double y, String text) {
GRect box = new GRect(x, y, BOX_WIDTH, BOX_HEIGHT);
// TODO: add() the box to the canvas
// TODO: create GLabel, center it in box and add() it
return box;
}```
@ Gary
At first glance i was a bit confused as to why you add the GRect in the method but then also return it But I can see that it is a very useful idea, add it and save it, makes perfect sense now i think about it. and i'm musing over my code for this exercise again. like you have said before Gary, code it, get it to work, then refine it.

@ the OP
there are many ways to do the methods and this is a great exercise to play with and discover new ideas. Rather than just simply completing this exercise, I think the you should play as much as possible with it,(at least till you get bored with it)

My own take on the exercise however is that a part of it is about being able to calculate where the boxes should be drawn(or centered) on the canvass by using code and starting out from from the origin (x=0, y=0), rather than manually measuring off the distances from the center of the screen.
(perhaps thats because i know whats coming next)
the target, checkerboard, rainbow, and this exercise are all similar in that respect. (ill PM the rainbow exercise to the OP its not in the 106a zip file and when you get bored with this exercise its something similar to target but something different to work on)

whilst i'm still a beginner and happily prepared to be corrected, to my mind
whenever something has to be done a given number of times, the idea of a for loop just seems to scream out at me. whether it's 4 times or 400 times.

the Switch code was very Ugly, but kudos for getting it to work, well done. I would never have come up with that. It Just goes to show that its not about a right way or a wrong way,, its about an appropriate way,
and its evident that the more you learn and the more experience you gain, the better able you become at determining whats appropriate..

kind regards
Sonny

EDIT: BTW does the OP have a name? cos referring to you as the OP just seems far to sort of formal, if not, can i just call you LJ?:D
Last edited by sonny; 05-15-2010 at 03:14 AM. Reason: added PS

9. Senior Member
Join Date
May 2010
Location
London
Posts
106
Rep Power
0
Thanks guys. I think I'll have a go at doing the exercise today - think I've had enough of a break! haha. I just didn't want to copy other peoples code, I want to understand it and do it by myself. I think I have a much better understanding on how to do the exercise now.

And Sonny, feel free to call me LJ ;)

10. Senior Member
Join Date
May 2010
Location
London
Posts
106
Rep Power
0
How does this look?

Java Code:
```/*
* File: ProgramHierarchy.java
* Name:
* ---------------------------
* This file is the starter file for the ProgramHierarchy problem.
*/

import acm.graphics.*;
import acm.program.*;

public class ProgramHierarchy extends GraphicsProgram {

public static final double BOX_WIDTH = 200.0;
public static final double BOX_HEIGHT = 80.0;

public void run() {

double horizontalMargin = (getWidth() - BOX_WIDTH * 3) / 4;
double verticalMargin = (getHeight() - BOX_HEIGHT * 2) / 3;

double x = horizontalMargin * 2 + BOX_WIDTH;
double y = verticalMargin;

GRect box1 = drawBox(x, y, "Program");

x = horizontalMargin;
y = verticalMargin * 2 + BOX_HEIGHT;

GRect box2 = drawBox(x, y, "GraphicsProgram");

x = horizontalMargin * 2 + BOX_WIDTH;
y = verticalMargin * 2 + BOX_HEIGHT;

GRect box3 = drawBox(x, y, "ConsoleProgram");

x = horizontalMargin * 3 + BOX_WIDTH * 2;
y = verticalMargin * 2 + BOX_HEIGHT;

GRect box4 = drawBox(x, y, "DialogProgram");

drawConnectingLine(box1, box2);
drawConnectingLine(box1, box3);
drawConnectingLine(box1, box4);

}

public GRect drawBox (double x, double y, String text) {

GRect box = new GRect (x, y, BOX_WIDTH, BOX_HEIGHT);

GLabel label = new GLabel (text, x, y);

x = x  + BOX_WIDTH / 2 - label.getWidth() / 2;
y = y + BOX_HEIGHT / 2 + label.getAscent() / 2 ;

label.setLocation (x, y);

return box;

}

public void drawConnectingLine(GRect fromBox, GRect toBox) {

double fromX = fromBox.getX() + BOX_WIDTH / 2;
double fromY = fromBox.getY() + BOX_HEIGHT;

double toX = toBox.getX() + BOX_WIDTH / 2;
double toY = toBox.getY();

GLine line = new GLine (fromX, fromY, toX, toY);

}

}```

11. that looks a lot better than your switch statement idea. Your methods have certainly improved.

to my untrained eye it looks a little confusing the way you keep re declaring x and y , if this was many more lines of code it might be difficult to keep track of x and y if you were trying to debug it.

heres an example from your code.
passing x and y to label's constructor is confusing if you are going to re-calculate thier values before adding the label.
you can construct the label like this, without x and y
then set location using the two expressions

Java Code:
```public GRect drawBox (double x, double y, String text) {

GRect box = new GRect (x, y, BOX_WIDTH, BOX_HEIGHT);

GLabel label = new GLabel (text);

label.setLocation (x  + BOX_WIDTH / 2 - label.getWidth() / 2 ,  y + BOX_HEIGHT / 2 + label.getAscent() / 2);

return box;

}```
I still think you need to think about using a loop because your run method is repeating the same thing four times just with different values
perhaps you could just try looping the bottom row of boxes, i dont think there would be a great deal of maths involved in that..
however i think that that would also mean a rewrite of the Gline method.

I wouldn't worry too much about using other peoples code.
if someone has already written it and its written well ,, provided you understand it, don't worry about using it.

as you will start to discover, the java language, things like GRect and GOval and the thousands of other classes - are classes and methods that someone else has already written for you to use.

i've attached a variation of assignment two with a rainbow exercise. some of the other exercises are slight variations on the assignment two you have been working on.

this is the outline of the way I went about doing it,
my run is only one line.. and i call getWidth, and getHeight and pass them to the first method, so i never have to call them again.
it would interseting to see how you approach it this exercise, because there is more repetiion than the target exercise but its very similar.

Java Code:
```public class Rainbow extends GraphicsProgram {
private static final int COLOURBAND = 20; //pixel width of each band of colour
private static final int TOTAL_ARCS = 7;

public void run(){
drawRainbow(getWidth(), getHeight());
}

private void drawRainbow(int width, int height) {

}

private GOval circle (double x, double y, double r,int i){
}

private Color arcColour(int i) {

}
}```
since doing this there is a little of snippet of code i've learned that will help you a bit more
Java Code:
`setBackground(Color.CYAN)`
Also do have a go at the mark dexter stuff its really good
Last edited by sonny; 05-15-2010 at 11:01 PM. Reason: code tags

12. Senior Member
Join Date
Mar 2010
Posts
952
Rep Power
8
Originally Posted by sonny
I still think you need to think about using a loop because your run method is repeating the same thing four times just with different values
perhaps you could just try looping the bottom row of boxes, i dont think there would be a great deal of maths involved in that..
however i think that that would also mean a rewrite of the Gline method.
I don't really see any repetition. He has to deal with the separate values somehow (the Strings and the x and y positions), and I don't see what he gains from trying to do a loop there. You could conceivably make it work with a loop, but I don't see how you'd make it any simpler. If there were twenty boxes on that row, I'd think differently. Then it would be worthwhile putting the Strings into an array or List, and then doing the box drawing, label drawing and connecting line drawing all in one loop, after a separate method to draw the top box. If the whole diagram were more complex than that, then you'd need a more complex model -- probably modeling the parent/child relationship between the boxes -- but we don't have that here.

Good call on choosing the right GLabel constructor, though, and run() could be simplified a bit like this:
Java Code:
```		double x = horizontalMargin * 2 + BOX_WIDTH;
double y = verticalMargin;

GRect box1 = drawBox(x, y, "Program");

x = horizontalMargin;
y += verticalMargin + BOX_HEIGHT;

GRect box2 = drawBox(x, y, "GraphicsProgram");

x += horizontalMargin + BOX_WIDTH;

GRect box3 = drawBox(x, y, "ConsoleProgram");

x += horizontalMargin + BOX_WIDTH;

GRect box4 = drawBox(x, y, "DialogProgram");```
-Gary-

13. ## point taken

point taken. :)

i think i'm prone to trying to solve problems in a procedural way that will still work even if a major change occurs, it comes from a background in Legal work where one has to examine the potential complexities that can arise in the procedure and plan accordingly.

i'm undecided as to whether this translates very well into programming.
Perhaps it gives me a tendency to over engineer things a bit, rather than simplify. But its been good to come back to this exercise as it was one i made such a mess of in the beginning.
Last edited by sonny; 05-16-2010 at 01:18 AM. Reason: punctuation

14. Senior Member
Join Date
Mar 2010
Posts
952
Rep Power
8
Originally Posted by sonny
point taken. :)

i think i'm prone to trying to solve problems in a procedural way that will still work even if a major change occurs, it comes from a background in Legal work where one has to examine the potential complexities that can arise in the procedure and plan accordingly.

i'm undecided as to whether this translates very well into programming.
Perhaps it gives me a tendency to over engineer things a bit, rather than simplify. But its been good to come back to this exercise as it was one i made such a mess of in the beginning.
Those are good instincts for programming, which is part of what makes this a frustrating exercise. I think this would be a good exercise to revisit a bit later in the course, after more exposure to classes and objects.

-Gary-

15. Senior Member
Join Date
May 2010
Location
London
Posts
106
Rep Power
0
Thanks guys.

Sonny, where did you get the newer version of the assignments from?

I guess once I've done with this assignment (if ever) I could go back and see if I can do those newer ones. I'm looking at exercise 4 in assignment 2 now (older version) ...is it just me or does this exercise sound easy? Or am I underestimating the task as always haha.

16. CS106A Programming Methodology

this is the website for the current intake.
the assignments and hound outs vary a little from whats presented on the video lectures
but its interesting different chanllenges.

17. Senior Member
Join Date
May 2010
Location
London
Posts
106
Rep Power
0
Thanks mate. Added to bookmarks ~

18. Senior Member
Join Date
Mar 2010
Posts
952
Rep Power
8
Originally Posted by Learning Java
Thanks guys.

Sonny, where did you get the newer version of the assignments from?

I guess once I've done with this assignment (if ever) I could go back and see if I can do those newer ones. I'm looking at exercise 4 in assignment 2 now (older version) ...is it just me or does this exercise sound easy? Or am I underestimating the task as always haha.
Yes, it's easy, but it's the first exercise to deal with console input and Exception handling.

-Gary-

19. Senior Member
Join Date
May 2010
Location
London
Posts
106
Rep Power
0
Is this ok or was I supposed to do it a different way?

Java Code:
```/*
* File: PythagoreanTheorem.java
* Name:
* -----------------------------
* This file is the starter file for the PythagoreanTheorem problem.
*/

import acm.program.*;

public class PythagoreanTheorem extends ConsoleProgram {
public void run() {

println("Enter values to compute Pythagorean Theorem.");

int a = readInt("a: ");
int b = readInt("b: ");

double c = Math.pow(a,2) + Math.pow(b,2);
double answer = Math.sqrt(c);

println ("c = " + answer);

}
}```

20. Senior Member
Join Date
Mar 2010
Posts
952
Rep Power
8
That looks fine. I had forgotten that the ACM libraries had readInt() and friends. You could simplify it a bit:
Java Code:
`		println ("c = " + Math.sqrt(a * a + b * b);`
...but yours is fine the way it is.

-Gary-

Page 4 of 6 First ... 23456 Last

#### Posting Permissions

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