Pages

Monday 6 June 2011

Mehran Sahami Handout #12 CS 106A October 5, 2007


Mehran Sahami Handout #12
CS 106A October 5, 2007
Assignment #2: Simple Java Programs
Due: 3:15pm on Monday, October 15th
Based on a handout by Eric Roberts
Your job in this assignment is to write programs to solve each of these six problems.
1. Write a GraphicsProgram subclass that draws a pyramid consisting of bricks arranged in horizontal rows, so that the number of bricks in each row decreases by one as you move up the pyramid, as shown in the following sample run:
The pyramid should be centered at the bottom of the window and should use constants for the following parameters:
BRICK_WIDTH The width of each brick (30 pixels)
BRICK_HEIGHT The height of each brick (12 pixels)
BRICKS_IN_BASE The number of bricks in the base (14)
The numbers in parentheses show the values for this diagram, but you must be able to change those values in your program.
– 2 –
2. Suppose that you’ve been hired to produce a program that draws an image of an archery target—or, if you prefer commercial applications, a logo for a national department store chain—that looks like this:
This figure is simply three GOval objects, two red and one white, drawn in the correct order. The outer circle should have a radius of one inch (72 pixels), the white circle has a radius of 0.65 inches, and the inner red circle has a radius of 0.3 inches. The figure should be centered in the window of a GraphicsProgram subclass.
3. Write a GraphicsProgram subclass that draws a partial diagram of the acm.program class hierarchy, as follows:
The only classes you need to create this picture are GRect, GLabel, and GLine. The major part of the problem is specifying the coordinates so that the different elements
– 3 –
of the picture are aligned properly. The aspects of the alignment for which you are responsible are:
• The width and height of the class boxes should be specified as named constants so that they are easy to change.
• The labels should be centered in their boxes. You can find the width of a label by calling label.getWidth() and the height it extends above the baseline by calling label.getAscent(). If you want to center a label, you need to shift its origin by half of these distances in each direction.
• The connecting lines should start and end at the center of the appropriate edge of the box.
• The entire figure should be centered in the window.
4. In high-school geometry, you learned the Pythagorean theorem for the relationship of the lengths of the three sides of a right triangle:
a2 + b2 = c2
which can alternatively be written as:
c = ba22
Most of this expression contains simple operators covered in Chapter 3. The one piece that’s missing is taking square roots, which you can do by calling the standard function Math.sqrt. For example, the statement
double y = Math.sqrt(x);
sets y to the square root of x.
Write a ConsoleProgram that accepts values for a and b as ints and then calculates the solution of c as a double. Your program should be able to duplicate the following sample run:
– 4 –
5. Write a ConsoleProgram that reads in a list of integers, one per line, until a sentinel value of 0 (which you should be able to change easily to some other value). When the sentinel is read, your program should display the smallest and largest values in the list, as illustrated in this sample run:
Your program should handle the following special cases:
• If the user enters only one value before the sentinel, the program should report that value as both the largest and smallest.
• If the user enters the sentinel on the very first input line, then no values have been entered, and your program should display a message to that effect.
6. Douglas Hofstadter’s Pulitzer-prize-winning book Gödel, Escher, Bach contains many interesting mathematical puzzles, many of which can be expressed in the form of computer programs. In Chapter XII, Hofstadter mentions a wonderful problem that is well within the scope of the control statements from Chapter 4. The problem can be expressed as follows:
Pick some positive integer and call it n.
If n is even, divide it by two.
If n is odd, multiply it by three and add one.
Continue this process until n is equal to one.
On page 401 of the Vintage edition, Hofstadter illustrates this process with the following example, starting with the number 15:
15 is odd, so I make 3n+1: 46
46 is even, so I take half: 23
23 is odd, so I make 3n+1: 70
70 is even, so I take half: 35
35 is odd, so I make 3n+1: 106
106 is even, so I take half: 53
53 is odd, so I make 3n+1: 160
– 5 –
160 is even, so I take half: 80
80 is even, so I take half: 40
40 is even, so I take half: 20
20 is even, so I take half: 10
10 is even, so I take half: 5
5 is odd, so I make 3n+1: 16
16 is even, so I take half: 8
8 is even, so I take half: 4
4 is even, so I take half: 2
2 is even, so I take half: 1
As you can see from this example, the numbers go up and down, but eventually—at least for all numbers that have ever been tried—comes down to end in 1. In some respects, this process is reminiscent of the formation of hailstones, which get carried upward by the winds over and over again before they finally descend to the ground. Because of this analogy, this sequence of numbers is usually called the Hailstone sequence, although it goes by many other names as well.
Write a ConsoleProgram that reads in a number from the user and then displays the Hailstone sequence for that number, just as in Hofstadter’s book, followed by a line showing the number of steps taken to reach 1. For example, your program should be able to produce a sample run that looks like this:
The fascinating thing about this problem is that no one has yet been able to prove that it always stops. The number of steps in the process can certainly get very large. How many steps, for example, does your program take when n is 27?

Mehran Sahami Handout #12 CS 106A October 5, 2007


Mehran Sahami Handout #12
CS 106A October 5, 2007
Control Statements
Based on a handout by Eric Roberts
This handout offers some additional notes on Java’s control statements (described more
fully in Chapter 4 of the textbook) that emphasize the important concepts. It also
describes a programming problem making use of various control structures.
To write programs, you need to understand control statements from two perspectives: you
must have a holistic sense of when to use them and why, but you must also learn to
understand the reductionistic details. For this big-picture perspective, you can rely to a
large extent on your experience from Karel:
• If you want to test a condition that requires an if statement in Karel, you need the if
statement in Java.
• If you would use the while or for statement in Karel, you will presumably use the
same statement form in Java.
The other holistic point that is essential about control statements is that the control line
is conceptually independent from the body. Thus, if you see a construct like
for (int i = 0; i < 10; i++) { Control line
statements Body
}
the statements in the body will be repeated for each of the values of i from 0 to 9. It
doesn’t matter at all what those statements are.
Boolean data
Another important topic is that of the data type boolean, which is the means by which
Java programs ask questions. In Karel, the counterparts to boolean are the conditions
such as frontIsClear() or beepersPresent(). In Java, the range of available
conditions is much richer and involves the relational operators and the logical operators
(both covered on page 78 of textbook). The most important lessons to take from these
sections are:
• Watch out for confusing = (assignment) with == (equality). This feature of several
programming languages (including C, C++, and Java) has probably caused more bugs
than any other.
• Be careful to understand both the interpretation and the evaluation order of the logical
operators && (and), || (or), and ! (not).
The time you put into making sure you understand boolean data now will pay for itself
many times over when the programs get more complicated later in the quarter.
– 2 –
Checkerboard problem
Create a GraphicsProgram subclass that draws a checkerboard in the graphics window.
The number of rows and columns are given by the named constants NROWS and NCOLUMNS,
and the squares should be sized so that they fill the vertical space. For example, if NROWS
and NCOLUMNS are both 8, running this program should produce the following output:
Graphics library documentation
The javadoc documentation for the ACM libraries is available under the “Links” section
of the CS 106A home page. Also, the methods in Figure 1 will help with the assignment.
Figure 1. Some useful methods in acm.graphics
Constructors
new GLabel(String text) or new GLabel(String text, double x, double y)
Creates a new GLabel object; the second form sets its location as well.
new GRect(double x, double y, double width, double height)
Creates a new GRect object; the x and y parameters can be omitted and default to 0.
new GOval(double x, double y, double width, double height)
Creates a new GOval object; the x and y parameters can be omitted and default to 0.
new GLine(double x1, double y1, double x2, double y2)
Creates a new GLine object connecting (x1, y1) and (x2, y2).
Methods common to all graphical object
void setLocation(double x, double y)
Sets the location of this object to the specified coordinates.
void move(double dx, double dy)
Moves the object using the displacements dx and dy.
double getWidth()
Returns the width of the object.
double getHeight()
Returns the height of the object.
void setColor(Color c)
Sets the color of the object.
Methods available for GRect and GOval only
void setFilled(boolean fill)
Sets whether this object is filled (true means filled, false means outlined).
boolean isFilled()
Returns true if the object is filled.
void setFillColor(Color c)
Sets the color used to fill this object. If the color is null, filling uses the color of the object.
Methods available for GLabel only
void setFont(String fontName)
Sets the font, as described in Chapter 5.
double getAscent()
Returns the height above the baseline.
http://jtf.acm.org/javadoc/student/index.html
http://jtf.acm.org/javadoc/student/index.html
– 3 –
Solution to the Checkerboard problem
/*
* File: Checkerboard.java
* -----------------------
* This program draws a checkerboard.
*/
import acm.graphics.*;
import acm.program.*;
/*
* This class draws a checkerboard on the graphics window.
* The size of the checkerboard is specified by the
* constants NROWS and NCOLUMNS, and the checkboard fills
* the vertical space available.
*/
public class Checkerboard extends GraphicsProgram {
/* Number of rows */
private static final int NROWS = 8;
/* Number of columns */
private static final int NCOLUMNS = 8;
/* Runs the program */
public void run() {
int sqSize = getHeight() / NROWS;
for (int i = 0; i < NROWS; i++) {
for (int j = 0; j < NCOLUMNS; j++) {
int x = j * sqSize;
int y = i * sqSize;
GRect sq = new GRect(x, y, sqSize, sqSize);
sq.setFilled(((i + j) % 2) != 0);
add(sq);
}
}
}
}

Mehran Sahami Handout #11 CS 106A October 5, 2007


Mehran Sahami Handout #11
CS 106A October 5, 2007
Simple Programming Patterns
Based on a handout by Eric Roberts
This handout summarizes some of the most common programming patterns that you will encounter in Java. Each of these patterns is covered in more detail in Chapters 2, 3, or 4 of the textbook, but it's good to have them in a simple handy reference as well.
The first set of patterns involves getting data in and out of the computer, which provide the necessary support for the input and output phases of a typical programming task. The patterns you use depend on the type of value, as shown in the following table:
Type
Declaration
Input pattern
Integer
int var = value;
var = readInt("prompt");
Floating-point
double var = value;
var = readDouble("prompt");
String
String var = value;
var = readLine("prompt");
The following patterns are useful in calculations:
English
Java (long form)
Java (shorthand form)
Add y to x.
x = x + y;
x += y;
Subtract y from x.
x = x - y;
x -= y;
Add 1 to x (increment x).
x = x + 1;
x++;
Subtract 1 from x (decrement x).
x = x - 1;
x--;
The most helpful patterns, however, encompass programming operations on a larger scale and help you establish the overall strategy of a program. The most important ones are described in the next few sections.
The repeat-N-times pattern: (page 101)
This pattern is the same as it was in Karel and is used for the same purpose.
for (int i = 0; i < N; i++) {
statements to be repeated
}
In Java, however, you are allowed to use the value of the index variable i in the body of the loop.
The read-until-sentinel pattern: (page 102)
This pattern is useful whenever you need to read in values until the user enters a particular value to signal the end of input. Such values are called sentinels.
while (true) {
prompt user and read in a value
if (value == sentinel) break;
rest of body
}

Programming Methodology-Lecture06 Instructor (Mehran Sahami)


Programming Methodology-Lecture06
Instructor (Mehran Sahami):All righty, welcome back. If you haven’t turned in the
assignment yet and you, at some point want to, turn it into that box up there.
So a couple quick announcements before we start. First of which, first of which is the
quarter is already 1/5 of the way over, right? After today it’s like two weeks of ten week
are over, so that’s hard to believe.
But there’s three handouts in the back including your next assignment because the fun
never stops; when one assignment’s due the next assignment goes out, and a couple other
handouts. Assignment one, as you know, is due today so please drop it off in the box in
front and, congratulations, you’ll all – well, assuming you didn’t take a late day you’re all
programmers, right? Because hopefully you all did, Karel, you got him to run around the
world and do stuff. Hopefully figured out some interesting out rhythms and now you can
turn it in. Question?
Student:I didn’t know if you needed a hard copy [inaudible].
Instructor (Mehran Sahami):Un huh, you want to get a hard copy in as soon as you
can, like right after class. But hard copies are important because we want you to turn in
both because we use the electric submission to be able to actually run it and your section
leader makes comments on the hard copy and so it’s important to have both.
But just because you asked…
All righty. So I want to take a quick pain pole before we start. So let’s actually dive into
the real sort of meaningful things. What the pain pole really is – remember I asked you to
think about how much time it actually took you to do the assignment? So total it up over
all the Karel problems; how many total hours; think about it, it took you to actually do the
assignment. Right? And we’re just going to go through and do a quick show of hands.
How many people actually got through the assignment in zero to two hours? All right.
Maybe like a couple people. I’ll make a small bar. How about two to four? A fair
number. Four to six? That’s good to see. Six to eight; eight to ten; ten to 12; 12 to 14; 14
to 16; 16 plus? Rock on. Thanks for admitting it. It’s a good time. Hopefully it was a
good time.
But that’s – first of all, one thing to note is the world is surprisingly normal. Right? Like
everything in the world is just normally distributed, that’s just the way it is.
The second thing is that computer programming, right or software engineering is a pretty
high variance event, right that you can go from less than two hours to 16 plus. I don’t
joke when I say it’s actually very high variance. But hopefully what this give you is
again, what we shoot for, right, is about ten hours per week outside of class for, you
know, work. We shoot for here and as I mentioned, you know, it looks like you’re all
doing real well because you’re sort of below the average point. The truth of the matter is
kind of as the quarter goes on, the assignments tend to get a little bit harder which means
you’ll actually see this curve kind of move down a little bit more into that range. This is
good times to actually see it here right now.
It also hopefully gives you a chance to gage for yourself how you’re doing sort of relative
to expectations. Right? If you’re sort of doing real – you know, hopefully you put in your
comments and it was good software engineering and everything and I’m totally willing to
believe it was and you just wrote your code and it just all worked and it was beautiful
and, sort of, if you’re done in this end, as long as you’re still feeling like you’re
understanding the concepts and you’re plugging away, that’s important and just keep
plugging and you will do just fine, trust me.
There have been times when I have been down here myself and it wasn’t fun when I was
there, but you just keep plugging away and it works out.
And but the important thing is if you were sort of in a particular range, even if you’re in
this range and things just worked but you didn’t understand why, that’s more dangerous
than being in this range and understanding why because all the concepts in this class will
build on top of each other. So make sure you understand the concepts not just that, oh
Karel happened to do the right thing. Yes, he got to the right spot in the middle of the
world, but now he’s just spinning around. That’s fine if he’s just spinning around, he just
got that middle spot, right. We’re kind of a lock, like you just throw in enough
instructions until I kind of did the right thing; that’s not real good understanding and you
want to talk to me, talk to your section leader, talk to the TA to try to clear that up.
All right, so with that said we’re just going to dive in because there’s a question in the
back.
Student:Is it an honorable violation if you look at someone else’s code once you already
both handed you assignments in and gotten it back?
Instructor (Mehran Sahami):Once you’ve gotten it back and it’s already graded, it’s
fine to actually be able to look at someone else’s code because at that point you can just
kind of, you know, share ideas.
All right, any other questions?
All righty, so a couple things to cover real quickly. Last time we talked all about methods
and some more about objects. There’s two things you should know in the programs that
you’re going to be doing, is we talked a little bit about one of them last time in terms of
how to get input from the user. There’re these functions that you should know about.
One is called READ INT and there’s some prompt inside double quotes that you give and
what that does is ask the user basically for an integer and gives you back some value that
you can say, assign to an integer. There’s also a version of this to get doubles, which
surprisingly enough is called RE DOUBLE and has exactly sort of the same properties.
So it’s called RE DOUBLE; it has some string here as it’s parameter or some text here in
its parameter inside double quotes which it displays to the screen and then gets you back
a value which is a double one you can assign to a double. Those are just two things off
the bat that you should know about because that’s how you’re going to get input, at least
for the time being, from the user in a lot of cases.
Now, one thing you want to do once you actually get some input from the user is, you
want to do some manipulation on it like some expressions that we talked about last time.
We talked about some of the different operators like addition, subtraction or unary minus,
it’s the same symbol, multiplication, division and my favorite, the remainder. And so we
talked about all those except for this little guy last time. All of the operators kind of work
the way you would expect them to, okay. And we’ll talk a little bit more about division in
just a second. The interesting thing about division – so all of these things work with both
– or I should say – all of these work with both integers and doubles. The remainder, as we
talked about, only works with integers, right because it doesn’t make sense to have a
remainder when you have real values.
These three guys work exactly the same for integers and double, just the way you would
expect addition, multiplication, all that happy stuff, to work. Division kind of rears its
ugly head because it actually works slightly differently if you’re doing division for
integers versus doubles. Okay? The whole point of that is, if you’re doing a division and
the two arguments that you’re dividing, right if both of these things are integers; in this
case I have integer constant which is what I mean, the values, right. If both of these
integers, what it does is integer division which means it does the division and throws
away any remainder. So what you get back is an integer. So 5 divided by 2 when these
are integers gives you back the Value 2. That little remainder thing is just gone. If you
want to get the remainder you use this guy. Okay?
If either one of these particular values happens to be a real value, like a double, then it
will do real-value division and give you back a real value. So if you happen to divide 5,
even if 5 is an integer, by the Value 2.0 and so it knows it’s a real value because it’s got a
decimal point in it, this will give you back 2.5 as a double and so you can assign that to a
double. Okay?
So if either one of the arguments is a double, you get real-value division; if they’re both
integers, you get back the integer portion. Un huh?
Student:I’m a little confused about the double; the double is just a real number?
Instructor (Mehran Sahami):It’s just a real number. Yes.
So another thing that kind of comes up when you do expressions – yeah, sometimes
you’re taking notes and you just don’t know; it’s like candy raining from the sky.
The other thing to keep in mind is just like arithmetic, sometimes you want operators to
evaluate in different order. There’s an order precedent for how these things actually
evaluate in case you have to have some big honking expression. The order of precedent is
you can have parentheses. Parentheses are the highest precedent. That means you
evaluate everything in parentheses first, then multiplication, division and the remainder
operator have the same level of precedents. And so if you have multiple of them; they’re
evaluated from left to right and then addition and subtraction. Again, if you have
multiple, evaluate left to right.
So it’s just like regular rules of precedent in algebra, which hopefully you’re familiar
with, but to make that concrete let’s say you have some integer X and we say X equals 1
plus 3 times 5 divided by 2. How does that actually evaluate?
Well first of all, we say do we have any parens? No we don’t have any parens. That
would be the highest level of precedence. You can always force something to evaluate
more highly by putting it in parens. So these guys are all at the same level, so we evaluate
left to right. So we come across and we say here, here’s multiplication, we evaluate this
thing as 15, right? We don’t do this addition first; this 3 times 5 becomes 15. Then we
divide it by 2. And, you remember what I just said? Hey, this is an integer, this is an
integer so this is integer division, so 15 divided by 2 in integer division is?
Student:Seven.
Instructor (Mehran Sahami):Seven. Rock on.
So this whole thing is 7 and then we add the 1 to it because addition has the lowest level
of precedence of all the operators here and what we get at the end of the day is that X is
equal to 8.
Okay, hopefully you can see that and if you can’t, I we’ll just tell you X is equal to 8. So
those are the rules of precedent. They’re exactly the same as, hopefully you know from
algebra. Un huh?
Student:Isn’t it true [inaudible] should be in parentheses?
Instructor (Mehran Sahami):It’s nice to clarify; it’s nice to always put in parentheses.
Sometimes you have to put in parentheses to get the right thing to compute and I’ll show
you that in just a second, but it’s nice now to just to fully parenthesize everything. Uh
huh?
Student:Where do exponents fall in there?
Instructor (Mehran Sahami):There is no built-in exponent operator. Okay? So if you’re
sort of like a mat-lab person or something like that there’re functions that we’ll get to
later on that compute exponents but there’s no build-in primitive operation for exponents.
Okay?
So with that said, sometimes there’s times in life when you say hey, but Marilyn, I have
these two integers but I really want to get some value back which is some real value.
Right? So what you can do is – let’s say I have INT X, okay? And let me give X some
initial value; so I can say X equals 5. Then I want to take like half of that and assign it to
some double Y. So if I say double Y equals X divided by 2, you might think, hey, this is a
double right, isn’t it going to do the right thing and give me back 2.5? No. It evaluates the
right hand side first and then assigns it for left hand side. So you have 5 here. That’s an
integer. This 2 is also an integer. It does integer division which means you get 2. Once
you get that 2 it says hey, but that two into a double and says, okay, it’s 2.0. So you’re
like, huh? That was totally weird, but that’s because it was doing integer division. So
what you need to do is, you need to tell it – you need to say, I want you to do real-value
division by temporarily treating one of these things as a double. That’s something that we
refer to at a cast. It’s kind of like you were making a movie and you need to come up
with a cast and you know, you get someone who’s going to like, play Harry Potter for
you, but he doesn’t really wear glasses so you say, for the purpose of being in the cast,
I’m going to put some glasses on you. For this one thing, you’re going to wear glasses
and then we’re going to take them off. It doesn’t change intrinsically who you are, it just
makes you appear different for this one operation.
And the way we do that is we specify the type that we want to cast to in front of the thing
that we want to cast. So we would say DOUBLE X divided by 2. All this means is, take
this thing, which is not normally a double, and for the purpose of this operation, treat it as
though it were a double. It does not change X from being an integer intrinsically; X
remains an integer after this operation, but now it becomes 5.0 and when we do the
division, we do real-value division, we get 2.5 and that’s what goes into Y.
Okay? So that’s what’s called a cast. You can also do that, interestingly enough – let’s
say you did that and now Y is some box somewhere that has the value 2.5 in it and you
say, you know what, I really like the integer part of Y. And so I’m going to have some
integer Z and I’m just going to set that to be equal to what I would get if I cast Y to be an
integer.
Well, if I cast Y to be an integer, you might say, oh Marilyn, does it round? Like do I get
3 because I remember if it’s a .5 we round up, that was always the way it was when life
was good. No. You don’t round up. As a matter of fact, it could be 2.9; it could be
2.9999, you still don’t round up. This is computer science. It’s not necessarily forgiving.
We always round down. You take the integer of a real value, it truncates it; it drops
anything after the decimal point; it doesn’t matter how big it is, sorry. It’s just like the
dollar; we just devalued your currency, right. It just – drop everything after the decimal
point. That’s life in the city. Okay?
So, if we go to the computer for a second, we can put this all together in a little program
and actually see what’s going on. So I wrote a little program that averages two numbers
and it’s running right now. I’ll show you the text for that program over here.
So here’s some program average two integers. I say this program averages two numbers;
I read in one number from the user; I read in another integer from the user and then I
come here, and notice I commented for you that it’s buggy, I say hey, the average is just
adding the two together and diving by 2 right? That’s what I remember with a
mathematical expression for average of two numbers when I looked it up in my book of
mathematical expressions for averaging two numbers. And then I write out the average.
So what’s the problem here? Uh huh?
Student:The [inaudible].
Instructor (Mehran Sahami):Yeah, so there’s two problems here. Da da daa. And then
we reveal the comment and there they are.
First, we need to parenthesize the expression because in terms of precedent, the division
has precedent over the addition. So if we were to say take the average of 5 and 6, we
don’t get 5.5, we get 8. Why? Because it took half of 6; it took that 6 and divided it by 2
and then added it to the 5. So it’s actually at – doing this operation over here first and we
want to say, hey, add some parentheses to force the addition to happen first.
Now ever after we force the addition, this whole expression here is still going to be an
integer because it adds two integers, that’s just going to give us an integer back and then
we divide that by an integer. There’s two ways we can fix this. One is, we can change the
2 to a 2.0, so we can explicitly say that that constant in there that we’re dividing by is real
value and that will force real-value division.
Another way we can do it is to say treat this whole thing as a double for this operation. So
after you add those numbers together you get something which is the total of those two
numbers, treat that total as though it were a double and then do the division. So if we do
that, then we’re good to go. Uh huh?
Student:If you put a double in there, do you still need that other double before you add
it?
Instructor (Mehran Sahami):If I put a double in where?
Student:Where it is now is now, [inaudible].
Instructor (Mehran Sahami):Uh huh, yeah because this is the type of average. Right?
So if average is not – I need to declare average first of all; I need to give it a type. If I
don’t give it a type double it can’t store a real number anyway. So that’s what that
double’s about. Uh huh?
Student:If you cast a double can you expect everything after to double on the line?
Instructor (Mehran Sahami):Yeah, it affects the most immediate thing after it. If it’s
parenthesized, it’s a parenthesized expression; it’s just one variable, it’s just that variable.
Uh huh?
Student:If the user enters a double into the computer, what difference would it make?
Instructor (Mehran Sahami):Ah good questions because someone wrote this little read
integer for us so let’s run it and see what happens because it’s just that smart.
So here’s – and one, we’re like hey, here’s 5.5, I want 5.5 and it says illegal numerical
format. Right? It has a big cow; it’s in red. Right? All that means is, I want an integer;
you didn’t give me an integer. Give it to me again and notice it prompts you again and
you’re like, okay, sorry. I meant the letter A. It’s still illegal in numeric format. I would
do that with like my friend’s computer; like you know, they write their programs and they
didn’t do like, nice error checking or whatever that all the READ INT stuff gives you and
they’re like, give me an integer and I’d be like, how about A. And they’d be like, we’ll
that’s not an integer and I’m like, to me it is. I’d put it in and watch their program crash
and, you know, I was mean. Yeah, there’s 5.5, it’s working. You laugh now, wait until I
do it to you. Uh huh?
Student:[Inaudible].
Instructor (Mehran Sahami):Pardon:
Student:[Inaudible].
Instructor (Mehran Sahami):There’s something you can do in java having to do with
formatting. We’re not going to get into that now. If you’re really interested, you could
come talk to me afterward.
Oh, , that’s going to be the goal for this class; to see if I can get one to stay up on the
camera.
All right, so with that said, hopefully you kind of understand the notices of castings for an
operation and the rules of precedence that are actually involved. There’s a couple
shorthands you should also know. Uh huh?
Student:[Inaudible] can I skip the top [inaudible]?
Instructor (Mehran Sahami):In that particular case with Z, you can skip the cast
because if it says, hey if you have Y here and you want to assign it to an INT, the only
way it can do that is to cast it automatically to be an INT, so it will do it for you
automatically.
Student:The site, the part that I want it to return it contains much information
[inaudible]?
Instructor (Mehran Sahami):Yeah, and so over here if you add a double and you try to
assign it to an INT it just – you can’t because it doesn’t have space; it doesn’t store
what’s after the decimal so it just truncates it for you. Yeah. I just put INT to explicit
about the truncation.
There’s a couple other things we want to do which are shorthands for arithmetical
expressions because there are some arithmetical expressions – arithmetical, is that even a
word? Arithmetic expressions – you’ve gotta keep me honest, sometimes I just make up
words. I’ll tell you stores about that at some point, but not right now.
Let’s say we have INT X, our old friend, after I told you all this stuff – good variable
name, everything’s X. So let’s say we say X equals 3. Now there’s a lot of things
sometimes you want to do with X. Something that we want to do a lot is to add 1 to X.
Right, so if we want it to add one to X, how do we do that?
Some people already know. We’ll do it the long way. X equals X plus 1. That adds 1 to X
and stores it back in X. Turns out, this notion of taking a variable, adding something to it
and storing it back to itself is very common and so there’s shorthand for doing that which
is X plus equals and then some value. So if I change this, say to a 5, and I said X equals
X plus 5, that’s the same thing as saying X plus equals 5. It just means take that value
that’s over here and add it to X and store it back into X. In the case of adding 1, it’s not
adding 1 because often times you want to count. It’s something we do so often there’s
even a special shorthand just for adding 1. Which, is X plus, plus. This may look a little
familiar to you from the Karel world. You’re like, oh, I remember I plus plus, is that the
same thing? Yeah, you were adding 1 to I in Karel’s world. Here you’re adding 1 to X.
So there’s no spaces here or anything, X plus plus just means add 1 to X. If you’ve ever
head of language C and C plus plus, that’s where C plus plus gets its name from. They
sort of started with C and the made it a little bit better by doing the plus plus. Okay?
You can also do sort of subtraction in a similar way. So if you want to subtract 1 from X,
that’s the longhand form of doing it, you can say X minus equals 1, which is a slightly
shorter hand and there’s a complete shorthand for it which is X minus minus, which
means subtract 1 from X and store it back in X. Okay?
There’s a couple other shorthands, you can also think about multiplication. So if you
want to say X equals X times 2, like you want a double 2, you could say X times equals
2. Same sort of effect, sort of a times equal. There is no super shorthand for, you know,
times equals 2, it just stops there. There is also divide equal, as you can image; so X
equals X divided by 2, X divide equal 2. You know, the value here is basically the value
there, so if you want to multiply it by 5, you would just put a 5 there, same kind of thing.
But these little shorthands – you can use these with integers, you can use them with
doubles, they work for both, you’re fine. Okay?
So besides the shorthands, these are just some little syntactic things you should know,
right. Hopefully all these things are fairly clear and they make sense.
There’s also a notion, kind of time for a new concept; the notion of a constant. I’ll write it
in big letters. And the idea behind the constant is it differentiates it for a variable and that
it does not vary, right. Variables vary, constants remain the same. And so you might
wonder why do I care about what is a constant, right? Like isn’t the value like 3 here a
constant? Yeah but some constants are meaningful and sometimes you want to give them
a name. So for example, PI. Right? PI is some constant that has a value like – let’s just
say for right now, 3.14. So in your program, you could have some double called a PI, all
upper case that’s the conventional use for constant, separate words have underscores to
differentiate them, equals 3.4. And you might say, oh that’s great, now anywhere in my
program, like if I’m computing like, you know, the area of a circle and it’s PI R squared,
right, I could just say something like, take the radius, multiply it by PI, multiple it by PI
again and this would be, you know, my – assuming I had R somewhere and I have area, I
could compute it like that. And oh, isn’t that so good. My program’s readable now, it’s so
good, I know – yeah, that’s all wrong. .
No one says anything, like sometimes I’ve gotta throw things at you to be like, is anyone
paying attention? Yeah, we just squared PI. PI R squared, remember that? Yeah, there’s
R times R times PI. I can just do this for computing the area and everything’s just fine,
right? And it makes it a little bit more readable. But the problem is PI is a variable here
right? Nothing prevents someone from coming along and saying, yeah, you know what, I
don’t really like your PI. I like my own PI and my PI is 6 because it’s just bigger. Right?
Then you go compute the area and your area got a whole lot bigger and you’re like,
why’s it so much bigger? I don’t understand. Right? Because someone changed your PI.
Get your hands off my PI, all right.
The way you want to do that is, you want to force PI to not change. You want to tell the
machine this is a constant. I will give you a value, it will remain unchanged. And the way
we do that just happens to have some sort of bulky syntax associated with it, but I’ll show
you what that looks like. Okay.
So the way we say that – sort of follow along. First, we say private because we want to
keep our constants to ourselves. So what private means is this constant I’m going to
define, I’m going to define the constant in a class. It’s not defined in a – you can define
one in a particular method, but generally we define our constants in our entire class – I’ll
so you where they go in just a second – and we say private because we don’t want anyone
to be able to see our constants outside of our class. So first, we say private. Then we say
static, which is just kind of a funky word which means that this constant sort of lives for
the class and there’s only one of these for the WHILE class. So it’s not like – you, if
you’re an object for the class, you don’t have your own version of PI and some other
object has their own version of PI. The way you can think it is, remember I told you a
couple days ago you’re all objects? You’re all objects and we have one constant, which is
the amount of mass in the world, or universe, right. And so you don’t have a separate
mass and I’m like, hey, I have my different amount of mass for the universe and it’s
different from your amount of mass for the universe. We share the same mass for the
universe. So all of humanity, or you could think of all objects that exists share the same
mass for the universe. That’s what static means. Everything of a class shares the same
thing. You don’t have – each object doesn’t have its own version. Okay?
Then, we say final, which means, get your hands off my PI. I’m going to give you a value
and it’s the final value. No one else is going to be able to give you a value. No one else is
going to be able to give you a value to this because the value I give you know is the final
value.
Then, we specify the type. Right? So we’d have DOUBLE for PI and then if we can
zoom out a little bit this is going to be a two-board extravaganza because it’s just that big.
Public, or private, static, final, double, name of the constant PI and then its value 3.14. So
all of that means you’re going to get something who’s of type double, it’s value’s not
going to change after I give its initial value, there’s only one of these for the entire class
and it only lives inside the class, but we just put all those things there just so you know.
Okay?
Now the important thing about doing this is you want to give your constants good names
and – well, good names is one reason, right, so when someone reads your program they
can say oh, he’s multiplying by PI, that’s a good time. The other thing is that it allows the
program to change easily. Right? So I could have an area computed somewhere; I could
have could have circumference computed somewhere else that also uses PI. I could go
somewhere else and do something somewhere else funky with PI and then someone
comes along and like some physicist comes alone and sees my program and says, oh, you
must be an engineer because you’re like 3.14. Like in physics, if we say 3.14, like
particles miss each other when we accelerate them to the speed of light. You’re like, well,
don’t accelerate particles to the speed of light. But they come along and they say, no, no,
no, no. PI is 3.14159622, there’s always a 2 before the 6. I’ll stop there.
I have a friend who actually has PI memorized the 400 digits. I was like, that was just a
tremendous waste of your time. . But that’s okay, I’m sure it’s probably useful
somewhere. If I really need to know, I’ll go ask him or I’ll write a program to compute it.
So we can get more exact values of PI, right.
The other thing that kind of comes up is that now, if I use PI all throughout my program,
I’ll I need to do is change it in that one place and I get more precision all throughout my
program. So that’s one thing in terms of nice software engineering, right? It changes
everywhere so I don’t need to go through and hunt down, oh, where did I put 3.14 in my
program and I have no inconsistencies because if everyone’s referring to that same
constant value, they’re all referring to the same thing.
The other thing you want to keep in mind, in terms of good names is think about names
that are readable. No joke, I actually worked on a program for a large corporation once
that will remain nameless, where this constant was in the program. I don’t know, he had
some extra stuff there and I looked at it and I was like, yeah, that’s very descriptive. 72
equals 72 and I was like, I was really tempted, I just wanted to come along and be like, la,
la, la, la,la. Like, does the universe end? Like what would happen? I have no idea where
this is getting used. And it turned out, what this – anyone want to venture a guess what
this was used for? It’s the number of pixels in an inch on most monitor resolutions.
That’s what it was. It was like this gooey program, or user-interface program and that’s
what this was because someone somewhere in some class had told them, hey, if you’re
going to have any values in your program other than 0 and 1, which are very common
and occasionally some other value will come up, like you want to divide by 2, it doesn’t
make sense to say this is the thing I use to divide by 2 and its value is 2, right. There’s
some values that come in your program that it’s fine to just have the actual number in
there. But other than these things, most numbers that appear in a program actually have
some meaning and you want to have them assigned to a constant. So this person probably
heard some rule somewhere that says oh, you should have constant for every value in
your program and they didn’t know what to name it so they just called it 72. That’s bad.
You want to give it real names for what it actually stands for.
All right, so any questions about any of this stuff? Uh huh?
Student:If the rationale like behind name constant and using that whole privacy thing
that so nobody can change it but like, to change, if you have like just double PI equals
3.14 you’d still have to go to like the guts of the program. So how’s it any better?
Instructor (Mehran Sahami):Well, the difference between this is that programmatically
no one changed it. Right? So if I just said double PI equals 3.14, somewhere in my
program someone could have come along and written this line and I can’t stop them.
Right? So I – it’s bad software engineering because I’m not preventing them from doing
this. This actually prevents them from doing this, so if they go into the program and say
PI equals 5, when they try to compile, the compiler’s going to uh huh, you told me PI was
final now someone’s trying to change it. Bad times. So that’s the thing. You always want
to force other people to also have good practice by doing stuff like this. Uh huh,
question?
Student:Is there a library that we can import that has standard constants?
Instructor (Mehran Sahami):There is a math library but for the purpose of this class –
if you’re really interested in math kind of stuff, come talk to me, but for the purpose of
this class, there’s some basic functions that are in the book and so you can use those, kind
of basic mathy functions but if you are really interested in other kinds of stuff we can talk
about it separately.
I need to push on a little bit so I’m just going to hold questions for just one second
because we need to go to an entirely different topic.
And the entirely different topic we’re going to go to is something called Booleans, and
there was a time when I told you about this type called Booleans, which is just the type
for variables whose value is true or false. So we can say BOOLEAN P and P will take the
values either true or false. Anyone know where the word Boolean comes from? Yeah,
George Boole. So know it and learn it.
I should ask if anyone knows how George Boole died? I asked this once, I’m going to say
it, he got sets of false. I thought that was kind of funny. He actually died of pneumonia
and the reason why he died of pneumonia – this is a true story – was he was out walking
one time from his house to the college where he was a professor and he was in the rain
and he got wet and he caught pneumonia and so when he came home, his wife actually,
who happened to be the niece of the person who Mount Everest is named for – just a
totally random side note – history’s just fun – so it turns out she had this belief that the
way you get over a particular illness is you experience the same conditions under which
you got the illness. So she’s like, oh you were in freezing rain, that’s why you got a cold,
so while he was lying in bed, she would get buckets of ice water and just douse him and
he died. So medicine’s come a long way; true story.
All right, so returning to our friend, the Boolean; Boolean has the value of true-false
which means what we want to do on the – when we assign something a – assign a
Boolean value to some Boolean variable, we need to figure out some expression that
evaluates to true or false. Right? It doesn’t evaluate to 5 or 10 or something, it evaluates
to true or false. Like, 3 greater than 5 is a true-false expression, right. You can look at this
and say Marilyn, 3’s not greater than 5, yeah, and the value of this is false and that’s what
gets assigned to P.
So there’s certain operations we can use called relational operations who, when we
evaluate them on two values, give us back something that its value extensively is true or
false. So let me show you some examples of that by going to the overhead. Let’s see my
little – oh, the remote mouse, I love the remote mouse.
So Boolean expressions is just a test, basically, for condition and it evaluates to true or
false. Right? You can actually use the words true and false in your program and say P
equals true, for example, those are actually parts of language.
So there’s a bunch of different value comparisons you can do, like equal equal, two
equals in a row, no space, is equals. It means like, does A equal equal B. It is not a single
equal. What does single equal mean?
Student:Assignment.
Instructor (Mehran Sahami):Assignment, right? When you say X equals 5, that’s an
assignment. When you say X equal equal Y, that is a Boolean expression that evaluates
the true if X and Y are the same. Not equal is exclamation point equal, or sometimes,
now that you’re all programmers, after Karel, this is called a bang. Because it’s kind of
like loud. It’s like bang, exclamation point. Right? Caught your attention, hopefully you
weren’t sleeping. If you were, you’re not. Bang equal means not equal and if you’re
familiar with some other language where you say like less than or greater than means no
equal, nuh, uh, not in Java baby, doesn’t happen.
All right, so then there’s greater than, less than, greater than or equal to and less than or
equal to. And the order of the symbols for these two actually makes a difference. But as
you can imagine, those are some common things you might want to consider for two
values to see whether or not, or two variables to see whether or not, for example, they
have equal value. Okay?
Now, Boolean comparisons, order of precedents, it turns out there’s a bunch of operations
you can do on Booleans. There’s an operation which is the bang, or the exclamation
point, which means not. That’s the logical not. So if you’re a logical person, this is
familiar to you. If you’re not a logical person, I’ll tell you what it means. If you put not in
front of some Boolean expression, or some Boolean variable like P, if P is true then NOT
P is false and vice versa. It just means give me the inverse of the logical value that P has
or whatever that expression would have been. Okay?
There’s AND, which is ampersand, ampersand. Get to know where your ampersand is on
your keys on your keyboard are. This is logical and. What that means, if I have two
Boolean expressions, P and Q, they can either be variables or expressions. P and Q is
only true if both of the sub-expressions P and Q are both true. If either one is false or both
are false, it is false. Okay?
And last but not least, there’s OR. If you’ve never used the vertical bar keys on your
keyboard, find them. You’re like, I may have never used them in my life. You will
probably use them for the first time in this class. Or, if I have two expressions P or Q, it’s
true if P or Q or both of them are true. So if either P or Q or both of them are true, then
what you get when you take the OR of them is also true. These are in order of precedents
so you’re NOT’s get evaluated first, then your ANDs, then your ORs. Much in the same
way the parentheses get evaluated first, then multiplication, division, then addition and
subtraction; same kind of thing.
So we can look at an expression, for example, Boolean P equals something like this.
Notice I’ve fully parenthesized it to make it a little bit more clear. X is not equal to 1 or X
is not equal to 2, so this might be a common thing you might think you want to do if you
want to say, well I want to figure out if X is not equal to 1 and X is not equal to 2. So if
it’s not equal to 1 or it’s not equal to two, isn’t that the right thing? And in fact, this is not
the right thing. This is buggy. P will always be true in this case. Why? Because if P’s
equal to 1, well the not equal 1 part is false but it’s not equal to 2 and that’s become true,
so yeah, false or true and it becomes true and vice versa if X equals 2.
So what you really want to say is, X is not equal to 1 and X is not equal to 2. That will
make sure if you want to make sure that X is not equal to 1 and X is not equal to 2. That’s
how you would write it although English people tend to say X is not equal to 1 or X is not
equal to 2 and so it’s confusing if you try to write that out in logic. This is what you
really want in that case. This is buggy. Okay?
Hopefully this gave you an example of a Boolean expression. Is there any questions
about this?
All righty, then let’s move on.
Short circuit – question?
Student:Where do you get the [inaudible]?
Instructor (Mehran Sahami):Just fine it on your keyboard, it depends on your
keyboard, but it’s a vertical bar, it’s somewhere on your keyboard. It will be and if it’s
not on your keyboard, throw your laptop away and get a new one and get angry at
someone, whoever sold it to you. It’s gotta be on there. Trust me.
Short-circuit evaluation. We actually stop evaluating Boolean expressions as soon as we
know the answer. What does that mean? Okay, so let’s consider something like this. P,
which is a Boolean, equals 5 is greater than 3 or 4 is less than 2. Well you know what, 5
is greater than 3 so as soon as we evaluate that part, that’s true. True or anything is true,
right? It doesn’t matter what the value of this guy is because we already got a true and
true or if anything is going to be true. So in fact, Java does an optimization and this
second test is not an evaluated at all. That’s why it’s called short-circuit evaluation. As
soon as we know the answer, we short circuit out and we don’t evaluate the rest of it. You
might say, oh, yeah Marilyn, that’s interesting. Why should I care? And the reason why
you care is there are sometimes making use of this actually makes a difference. So here’s
a useful example. That’s a not-so useful example. Where’s a useful example?
Let’s say you want to avoid dividing by 0 because dividing by 0 is an error. You can say,
well P is equal to; X is not equal to zero; if X is equal to 0, this is false. False and
anything is false so you want to evaluate the second part over here and you’ll never
actually divide by the 0. If X is not equal to 0, this is true. So to know the value of true
and something else, it needs t actually come over here and evaluate the second part
because it got a true for the first part it needs to know that this is true. But if it evaluated
the first part and got past it, you know that X is not equal to 0 so you won’t divided it by
0. Okay? So these kinds of little tricks are actually used sometimes in code and it’s called
– sometimes it’s called a guard to prevent this from happening. But that’s why shortcircuit
evaluation is something you should actually know about because you can actually
use it for usefully things. Okay?
Any questions about that? Any questions about Booleans or the operations or that kind of
happy news? Uh huh?
Student:What happens if you divide by 0?
Instructor (Mehran Sahami):If you divide by 0 you – usually you’ll get – well, you will
get an error, you’ll get an exception but we won’t talk about exceptions just think of it as
an error.
So let’s actually move on. We’re just going to cruise through tons of stuff today because
life is just good.
So it’s time to talk about statements. Okay? Just like in Karel when you had statements
like, move and turn left and all that happy news, now we’re gonna do all that happy stuff
in Java as well. Okay?
So one thing we first need to know about is this thing called a statement block, or a
compound statement. They are referred to as the same thing. Usually I say block, the
book likes to say compound statement, it’s just a set of statements enclosed in braces. So
you have some opening brace, a bunch of statements and then a closing brace. This is
what we would refer to as a block. Why do we care about blocks? The reason why we
care about blocks is, remember when we declare variables, a variable has something
called a scope. All a scope is – the way you can think about it, it’s not a mouthwash – the
way you can think about scope is that it’s the lifetime of the variable because variables
come into the world when they’re declared and one thing I didn’t tell you is that at some
point variables die. It’s very sad. But where a variable dies and lives is the block in which
it is declared. So when we say X equals 5 up here, X is alive until we get to the end of the
block in which X was declared. Which means when we get to a closing brace, that X goes
away. That’s it’s scope, or it’s lifetime. Okay?
If we declared X outside of these, the scope, it would not die when it came here. But if X
was declared out here, this scope is some which is referred to as an interscope. X is still
alive inside the interscope and it does not die when we get it out. It just dies when we get
to the closing brace of the scope in which X was declared. Uh huh?
Student:Can you declare a final end [inaudible]?
Instructor (Mehran Sahami):It – well it doesn’t die because of where we declare it. So
if we declare it inside a method, it could die when we get to the end of the method. We’re
going to declare it in the class so it’s never actually going to be at the end of a method so
it won’t die, it will be alive for the whole time that class is alive. Uh huh?
Student:When you declare [inaudible]
Instructor (Mehran Sahami):Uh huh.
Student:Will it actually pull out of the sub block?
Instructor (Mehran Sahami):Yeah, as long as the variable’s declared outside of the sub
block, that’s fine. And well – this is kind of technical point and sort of, in most intensive
purposes you don’t need to really worry about the nuances here but it’s just something
important to remember and we’ll look at some examples as we go along.
So other statements you should know about; the IF statement. You’re like, oh, IF, it’s just
like Karel, and yeah, it’s just like Karel, right? We say if some condition, and that
condition is something that evaluates to true or false. It can be a Boolean variable or it
can be some Boolean expression, anything that evaluates to true or false. So you can use,
and, or’s, not’s, all that happy news, now in a condition and then you have some opening
brace and close brace just like Karel and if the condition is true the statements get
executed. So we want to check if something is even, we can say if that number, when it’s
divided by 2, if it’s remainder equal the 0? Its remainder is equal to 0 and it’s divided by
2, it’s even so we’re going to write out NUM is even.
Now notice here, I don’t have the braces and it turns out there’s this one special case that
says if you have an IF statement, and it actually applies to a couple of other things, and
it’s only – the body is only one statement, you don’t have to have it inside braces. If it’s
more than one statement, like this, then you have to have the braces. So this is just a
special case that exists. But I like to think of use braces with IF; you have to if there is
more than one statement inside the braces. But I like to think of something that I refer to
as the orthodontist rule. Right? What do the orthodontist say when you go to an
orthodontist? You need braces. Right? It doesn’t matter if your teeth are straight or you
only have one statement or whatever, you need braces. It’s always a good idea to use
braces, which defines a block, right, so this now is a block, even if there’s only one
statement in the IF. There’s only one special case that I’ll show you in just a second, but
in general always use braces. Right, think orthodontist. Always use braces, it’s just a
good idea. Okay? Any questions about IF? Hopefully not because you hopefully were
using them a lot with Karel.
We have the IF ELSE’s just like Karel. Same kind of thing going on here. We have some
condition, either we do the statements or we do the ELSEs part if the condition is false.
So if we – the remainder of NUM divided by 2 is 0, we say NUM is even; or if the
remainder is 0 and if it’s not then we know it’s odd and we write out NUM is ODD and
so are you. All right? So not a whole lot of excitement going on there. You saw this in
Karel; same thing exists in Java, now it’s just a little bit different because you’re not
checking a front that’s clear anymore, all right. We’re not in Kansas anymore. You’re
actually doing some Boolean expression for that condition.
Let me just give you a couple more and then we’ll take some questions. There’s
something known as the cascading IF. This is kind of funky. A cascading IF says, what I
want is I’m going to check for at least just one condition to be true. I’m going to start off
with something that looks like a regular IF. This is like high school grading, right? If your
score is greater than 90, then print out A. Otherwise ELSE and what are we going to do
with the ELSE? We’re going to do another IF. ELSE IF your score is greater than 80,
print out B; ELSE IF your score is greater than 70, print out C and otherwise it’s kind of
– bad times. All right?
So if you think about this, only one of these IFs gets executed. Why does that? Because if
we come up there and we say score’s greater than 90, we do this. We skip the ELSE part.
Well, what’s the ELSE part. The ELSE part is everything else. Why is it everything else?
Because it’s an ELSE and then it’s one statement, right. There’s no brace here.
Remember I told you, if you have no braces it’s one statement. Well what is that one
statement? It’s an IF followed by an ELSE and that ELSE has one statement contained
within it so it’s part of this bigger IF and that has an ELSE which is contained as part of
that IF. So all of this stuff, in some sense, all cascades down. So if I do the IF part up
there and I don’t do the ELSE, I skip over this whole thing. If I don’t do the IF part, then
I come and I evaluate the ELSE which means I evaluate this first condition and it’s true
then I print out B and I skip the rest. If it’s false, then I evaluate the next condition. So
this is just sort of the idiomatic form – or a pattern form that you see, it’s called a
cascaded IF for when you want to check a bunch of conditions in sequence and the first
one’s that true does its IF part and the it skips the remainder of it. It’s so useful for things
like grades where you’re like, is it greater than 90? No. Is it greater than 80? No. Is it
greater than 70? As soon as I find one I’m done. Otherwise, I have some catch all at the
end if it says things are bad. All right?
So that’s the cascading IF. There’s something called a SWITCH statement. I’ll touch on
this very briefly. The SWITCH statement you can get it in excoriating detail in the book.
It’s just kind of nice for you to have. You can actually do anything with the SWITCH
statement – anything you could do with a SWITCH statement you could also do with IF
statements so it’s just kind of a nicety.
The way the SWITCH statement works is, it says IF you have some integer value, so here
we’re going to ask user for day of the week, right, and the first day of the week in Day 0,
which is Sunday. So they enter some number hopefully between 0 and 6 and we say
depending on what number they entered – so that thing that goes inside the parens for a
SWITCH statement has to be an integer value. Okay? Has to be an integer value.
There’re some other things later on in the class where we look at the boil down to integer
values but it cannot be a double, interestingly enough. And we specify the syntax goes
like this, case, then what value matches that case. So this is Case 0. And you have
sequence of statement until you hit something called a break. So notice, this is funky
because the only braces here are this brace down here and that brace up there which
encloses this whole SWITCH statement. There’s no braces in the middle. The way it
knows where to stop inside a SWITCH, so if someone enters 0 it says let me find Case 0.
Oh, here’s Case 0. I start executing from this line and keep going until I hit a break.
When I hit a break, I jump out here to the end of the closing brace. So if the user types in,
let’s say 6, it says it is Case 0, no, so it skips that. Is it Case 6? Yeah, so it prints out
Saturday and then it breaks which means it skips to default. If they enter any other value
other than 0 and 6 it says does it match 0,no, so it skips that; does it match 6, no, so it
skips that; it comes to the default with is kind of the be-all if it doesn’t match any other
cases and it rights out hey, it’s a weekday. Okay?
So you can do this with an IF, right? But this is just a nice way – there’s a lot of times –
the idea is to think like you have some mechanical switch and you’ve got to pick one of
the options and that’s why it’s called a SWITCH statement. Uh huh?
Student:Do you have to do in that order, or...
Instructor (Mehran Sahami):No, your order can be anything that it wants. You can
have – you know, the things can even be out of order. So they don’t even need to be
sorted. Was there a question in the back? Uh huh?
Student:[Inaudible].
Instructor (Mehran Sahami):Pardon?
Student:Can you break out of the method?
Instructor (Mehran Sahami):You can’t break out of the method all it does is break out
of the switch, so it just takes you – you start executing it at that bottom brace again. You
don’t actually leave the method that you’re in.
Student:But if you have like a…
Instructor (Mehran Sahami):Let’s take it off line. Let’s take it off line. Uh huh? Was
there another question over here? All right. Let’s press on then.
So in terms of four loops, you’ve also seen before hopefully in the context of Karel, so
we’re just zooming through. The way the four loops looks like, here’s the general form of
the four loop. It has four, just like you saw before in Karel and now it gets a little bit
more complicated but not much.
We have something called the INIT. What the INIT is, is when you come to a four loop,
it does whatever statements are in that INIT once and only once at the beginning of the
loop. Okay?
Then you have something called the condition. The condition is checked every time
before we go through the loop. So the first time we come to a four loop, we do the INIT,
we check the condition. If the condition, which is a Boolean or it can be any Boolean
expression and it’s true, we execute what’s in the loop. If it’s not true, we skip over the
loop and just execute immediately after that closing brace. Okay? So similar with what
you may have done with Karel, for example, except in Karel you probably executed some
number of time. And the step – so we execute the statements inside the loop only if the
condition is true. And the step is done every time after the loop. Okay? So what does that
mean? This is kind of a whole bunch of stuff to keep in mind. Let me just give you a
simple example.
Here’s a loop that you may have written sort of in the Karel world except now we’re
going to print out the value VI instead of making Karel do something, right? So this was
a form of syntax used for Karel to do something five times. Remember that? If you
remember that nod your head. Yeah. Hopefully.
So what is this really doing? Right now we can pull back the covers. Well the INIT was
to say create some new variable named I and set its initial value to be 0. The test you
were doing was to say as long as I was less than 5 execute what’s inside the loop. And the
step says every time you go through this loop I plus, plus. Add 1 to I and store it back to
I. So when we execute this, what happens? The first time it comes to execute it says I
equals 0, it checks to see if 0’s less than 5. It is and it says okay, I execute the loop so it
prints out a 0, adds 1 to I and goes back and checks the test. So you can think of the I plus
plus as happening after it’s executed the statements in the loop, but before it does the test
again. So now it adds 1 to I, I has the Value 1, it’s still less than 5, it prints it out, it adds
1 to I, it’s now 2; less than 5, it prints it out, adds 1 again, it’s 3; it prints it out, adds 1
again, it’s 4. Now after it prints out 4, it adds 1 to I again. Now I has the Value 5. It
checks the test again. Is 5 less than 5? No. Five is not strictly less than 5 so it’s done.
Okay, so you get the values from 0 to 4 but notice it still went through the loop five
times. It did the body; we just started counting at 0.
And as computer scientists, that’s a very common thing to do is, really when you want to
count something 10 times, you count from 0 to 9 instead of from 1 to 10. That’s just what
we do because zero’s a real number and we love it, we care about it. Uh huh?
Student:Is the scope of I is the four loop after we’re done?
Instructor (Mehran Sahami):Good question. Exactly, the scope of I is the four loop. So
when that four loop – oh that was real bad – when this four loop is done, I goes away.
Okay? So the lifetime of I is until we get that next closing brace in the scope of which I’s
the clairton. Sort of, we think of the scope of I’s being the four loop so when we get to
the end of the, when the four loop is finished executing and we sort of move on down
here, I is gone away.
But we can create another one in some other loop, that’s fine.
There’s other funkier things we can do with the four loop rather than just counting from 0
up to some value. We can actually start with a value like 6 and count down. So we can
say I’s initial value is 6, as long as it’s greater than 0, subtract 2. So we’re going to use
sort of that minus-equal-to funkiness. And so when we start off, I starts with the Value 6.
Six is greater than 0 so it writes out 6, subtracts 2, 4 is great than zero, it writes it out,
subtracts 2 again, 2 is great than zero so it writes it out again, and it subtracts 2 form I and
so now I have the Value 0. Zero is not greater than zero so, it’s done. Okay? So that 0 is
not displayed because after we do the step, we always check the test again before we
execute the loop one more time. Okay? Any questions about that?
So let’s do the WHILE loop super quickly because you’ve already seen the WHILE loop
in Karel’s world. Same kind of thing. While condition, if that condition is true we execute
some statements. The condition’s checked before every iteration of the loop, just like in
Karel. Right? So that’s why we did all this stuff in Karel because it carries all over
directly in Java and we execute the statements only if the condition’s true.
Let me show you an example. X starts with a Value 15 while X is greater than 1, every
time through we’re going to divide X by 2 and write out the value. So first time X has 15,
15 is greater than 1, we divide by 2, we do integer division so we get 7, we write that out
and go back up there. Seven’s greater than 1, we get 3, we do it again, we get 1, when we
do 1 divided equal 2 what do we get?
Student:Zero.
Instructor (Mehran Sahami):Zero, which is not greater than 1 so we’re done. Okay?
Nope, let me go back. Nope, let me just end the show. All right, so any questions about
the WHILE loops and we’ll review our friend the loop and a half next time. All right. So
I will see you next week.
[End of Audio]
Duration 50 minutes

Programming Methodology-Lecture05 Instructor (Mehran Sahami)


Programming Methodology-Lecture05
Instructor (Mehran Sahami):All righty. Let’s go ahead and get started. A couple of
quick announcements before we start today – so hopefully you’re all busy working away
on Karel and life is good. Just quick poll – how many people have actually finished Karel
already? Oh, yeah. I won’t ask how many people have not yet downloaded Eclipse. There
are no handouts today. Getting’ a little breather – no handouts. Don’t worry; you’ll get
some more of that next time.
Sections start this week, so hopefully you all should have gotten an email about your
section assignment and who your section leader is, so you can actually do Assignment
No. 1, the email portion. You should have been able to do the programming portion the
whole time. But make sure to go to section this week.
And the other thing is the Tresidder Layer, which every once in awhile you’ve heard me
refer to. This is a computer cluster up in Tresidder. Is staffed by one of six helpers like
almost continuously around the clock or most of the times at reasonable times when
people are working.
So Sunday through Thursday, every day except Friday and Saturday because contrary to
popular opinion, computer science people actually do have lives or we actually like to
pretend we have lives, but every day from Sunday through Thursday 6:00 p.m. to
midnight there will be a staff of helpers on there and actually some of the times there is
like two or three or four people there.
And they’re there just dedicated for the 106 classes. They’re not like general consultants.
They’re just there to help you work out problems in this class, and they know like what
assignments you’re working on, the whole deal. They’re all like, your section leaders and
they’re all be exceptionally trained to do this.
The other thing that’s going on, hopefully you should be doing Assignment No. 1. I’ve
actually gotten a bunch of Assignment No. 1 emails that have already come in. In the
early days, when I got the first few, I actually tried to respond to them all, but then at
some point, I just woke up and I like, you know, went to my computer and was like, “Oh,
you’ve got mail.’
And it just [inaudible]. So I couldn’t respond to everyone individually. I apologize if I
don’t respond to you individually, but I do read them all. I guarantee you that I actually
read them all and I look at backgrounds. And just to prove to you that I do, here’s some
interesting ones that have come in so far – just to share three.
So there’s someone actually spent their time in Taiwan living in a Buddhist monastery,
which I thought was interesting, except for the fact they were actually living there as a
monk whom I thought was pretty interesting.
Someone else used a – I wasn’t quite sure on this concept, but maybe I can provide a
clarification. There was a vegetarian who only eats low-quality meat, and so he
mentioned that as things like burgers and not steaks. And I would qualify that by saying
that’s not a vegetarian; that’s called being a grad student.
And last, but not least, there was actually someone in here who’s on the Colbert Report,
which I thought was actually pretty interesting. I don’t know in what context, but come
talk to me afterwards.
So with that said, any questions about anything before we start? Today we’re actually
gonna go over some of the graphic stuff you saw, talk a little bit more about objects and
classes and get into variables and values and all kinds of goodies. Any questions?
All righty, then let’s just dive right in. So one of the main topics for today is this thing
called a variable. And a variable, you know, like variables come up in mathematics and
it’s like, oh X and Y are variables, right and there are these things and we do all these
manipulations on variables.
In the computer science world, they’re really friendly, right, and you don’t have to worry
about integration or differentiation or you know, those kind of variables. Variables are
kind of your friend, and basically all the variable is in the computer science worlds is it’s
a box. It’s a box where we stick stuff and the stuff we stick into that box can change.
That’s why we call it a variable because it’s a box that has a variable contents, and you
think back you know, in the days of yore in math, and you know, oh yeah, it’s kind of
like X can have different values, yeah, it’s basically just like that.
So in computer science, what we think of as a variable, is each variable has three things
associated with it. It’s got some name, and that’s just how we refer to that particular box.
It has a type, which is something a little bit different in mathematics, but the type
basically says what kind of thing does this box store? Some boxes store numbers; some
boxes store letters; some boxes will store other things, like little objects in the world. But
a type is just what’s stored in that box.
And then there’s a value, and the value, as you can imagine is just what’s in the box.
What is the actual thing that’s in there, right? If it stores the number, then it might store,
for example, the Value 3 and that’s just the value, and it may have some name associated
with it.
And how do we actually name these? There’s actually a rule and it’s not a very
complicated rule, but a very simple rule you need to remember for what are valid names
for variables in Java. So a valid name, so this is how you actually name these puppies,
has to start with a letter or an underscore. So it starts with a letter like one of the
alphabetic letters and can be upper or lower case or the underscore character.
Okay, and that’s kind of you know, underscore. It’s down at the bottom of the line, okay?
And then after you have that initial letter or underscore, then after that, you can have any
number of letters, numbers, that’s like the number digits, like 1, 2, 3, 4, you know, 0, etc.
or underscores, okay?
So you can’t start with a number. You have to start with a letter or underscore, but for
most purposes in this class, just thing about them as letters. When not actually using
underscores, you might occasionally use numbers. You can actually have numbers after
the first letter.
There is one slight caveat to this rule which you can’t have any variables that’s name is
the same as some which known as a reserved word in Java, which means its name can’t
be the same as some special word in Java, like the word class is a special name in Java,
and there’s actually a page in your book, I think in Chapter 2, that lists all the special
names. It’s like out of the English language it has about 127,000 words. I think there is
like 40 in Java that you can’t make a variable name.
Okay, you have lots of other choices. As a matter of fact, there’s lots of things that don’t
have to be valid words in English. They can just be any name that follows this rule. The
important thing to think about in terms of a name and this is one of the good software
engineering principles, is make your name descriptive. If you have a program that’s
maintaining for example, the balance in the bank account, a real good name for the place
where you store the value of the balance would be something like “Balance.”
A real bad name would be something like “A,” because no one knows what A is. It’s like
hey it’s A – yeah, I know what A is. And someone says, “Yeah, A is balance,” and
someone says, “No, no, no, in my program, A is actually how many miles I bicycle
today,” and you’re like, “No, no, no, man, A was balanced.” Well, if it’s called Balance,
there’s just no ambiguity, so give them descriptive names.
So that’s kind of a name part of this. The next thing is what is this type all about. What
are the different types that you can actually have. And there are some things that we refer
to as primitive types. These are the types that have the smaller developed brains and use
knuckles drag on the ground. No, there just the types that are built into Java, okay and
some of the basic types we have is something we call an INT, which is short for an
integer, but we actually write INT, so INT, I-N-T, is the name of the type, okay.
And this is just an integer of value. It’s just gonna store some whole number basically. It
stores a number between minus 2 billion and plus 2 billion, but for all intents and
purposes, you can just imagine you can store any integer in there, okay?
There’s also besides integers what other kinds of numeric data do we have? People
already know, it’s like I would think it would be like real values, but a bunch of people
are already saying double because you’ve read ahead and you’ve done the assignment the
way you should. And that was kind of a mini social, but both went to the same person.
There’s this thing called a double and a double is actually some real valued numeric
value, right. It’s something like 2.3 is a double or even 2.0 can be a double, okay? Why is
this thing called a double – anyone know, as opposed to like a real? Uh-huh?
Student:[Inaudible].
Instructor (Mehran Sahami):Yeah, there’s this wonderful verb people call the I triple
E, which is like the Institute for Electrical and Electronic Engineers and they come up
with all these standards for things. Is anyone a member of I Triple E here? No one? Oh,
man, join and pay your dues. It’s a good time. I'm not actually a member myself.
But what those folks actually do is they come up with standards for things and one of the
standards they came up with is how you represent numbers that are real valued numbers
inside a computer, right, because remember a computer only understands ones and zeros,
so how do you actually represent a real valued number.
And so there’s a standard, and part of that standard has to do with a precision of the
number, how many digits in some sense and a rough approximation you store and double
stands for a double precision real number.
And so for the purpose of this class, all real valued numbers that we’re gonna use are just
of type double. Okay, there’s a couple of other types that I’ll just mention now and we’ll
actually go into them in much more detail in a couple of future classes.
One is called Boolean. And if you’ve ever heard of Boolean logic, this is a logical value,
so this is just essentially true or false, and we’ll talk about that in excruciating detail next
time, but I’ll just let you know that there’s a type called Boolean.
There’s also a type called care or Car and as you can imagine it’s because we like sort of
the first syllable of most things and this is the first syllable of character, okay, and so
we’ll also talk about this in a couple of weeks time when we actually get into a some
things with characters, but that’s just a character.
It’s a variable; it’s a box, but still is a character. It’s a box that stores an integer, box that
stores a real value, box that stores true or false and a box that stores a character. Those
would be the different types of them.
So one thing people – so that’s kind of types, at least some of the basic types. And then
when you think about value that we actually store in this box, people always get
uncomfortable when they see INTs and they see double, right, and they sort of say, “But
Meron, like 2 is an integer, right?” And I'm like, “Yeah.” And they’re like, “But you just
told me 2.0 is a double, right?” And I'm like, “Yeah, 2.0 is a double.”
And so the natural question is why? Why do we have both these things? How come like
all integers aren’t subsumed by the real values, right, you’re kind of the mathematician
type and you’re like, “Yeah, there’s like strictly more of these than there are of these. So
why are all these like subsumed in here. Why do we have this integer type,” okay? And
the reason we do boils down to a simple question and the simple question you want to ask
yourself is how much versus how many, okay?
So if you ask someone, let’s say you, ask me, just so I won’t embarrass you, “How much
do you weigh, Meron?”
Student:How much do you weigh, Meron?”
Instructor (Mehran Sahami):I weigh about, you know, 155.632 pounds, okay? That
makes perfect sense, right. If I can put a decimal point, I can put as many numbers after
it, or I could just say 156, right and those are both valid kinds of things.
Now you could ask me, “Hey Meron, how much children do you have?” I have 2.3
children. Does that make any sense to you? Yeah, it’s like we had three until that grisly
accident. No, it’s just that there’s sometimes – I know that’s horrible to say. We actually
have one, and he’s just fine.
There’s sometimes in the world when you care about counting, and when you care about
counting, it doesn’t make sense to have fractional values. Those things are integers.
They’re a how many kind of value. When you’re thinking about how much, that’s a
double value, and you actually want to keep these distinct because if I ask you what’s the
next number after 1, you say –
Student:2.
Instructor (Mehran Sahami):2 because you’re thinking integer, and that’s perfectly
right and if I say what’s the next number after 1.0, you say –
Student:[Inaudible].
Instructor (Mehran Sahami):Yeah, you start mumbling and you’re like, “Well, I know
it’s not 2.0. That would have been the obvious answer and that’s probably not it. How
about 1.0000001, and I'm like, “No you missed a couple of zeros in there. Just keep
going. Wait until the end of the quarter and put that 1 and come back and talk to me.”
In real values, there is no next value, okay, so when you care about counting, it doesn’t
make sense to use a double. That’s when you want to use an integer, so having these
things be a distinct type actually make sense and you’ll kind of see that as we go along,
okay.
So the value is basically just what you’re actually gonna put into this box over here and
it’s gonna be some of the values that we actually talked about, so let me show you some
examples of how we might use variables, what the syntax for variables actually is in Java.
So what we need to do with variables before we use them in Java is we need to declare a
variable. It’s kind of like declaring your love. If you’re gonna have some box somewhere
that’s got something stored in it, you need to come tell the world, “Hey world, I’ve got
this thing called X. It’s cool. Check it out.” Here’s how you do that in Java.
You say INT X, okay? What that does is you specify a type for your variable, what’s the
box gonna hold. You specify a name for that variable. In this case, the name is X and
because all statements end with a semi colon, just like you saw in Karel’s world, we put a
semi colon.
What does this do? It creates a box somewhere in the computer’s memory that’s name is
X that’s gonna store an integer in it. Right now, what does it store?
Student:[Inaudible].
Instructor (Mehran Sahami):Nothing. We haven’t told it anything to store in particular.
And so in Java’s world, unless you initialize you always want to think about initializing a
variable, giving it some initial value to start off with and there’s some rules that we’ll talk
about as we go along regarding when Java will automatically sort of give you a zero
value in there and there’s time when it doesn’t and sometimes it can get a little bit
confusing.
So the general rule you want to remember and it’s also good software engineering is give
variables an initial value when it makes sense, okay? So how might we give it an initial
value? Well, on that same line, rather than just putting the semi colon there, we could say
X equals 3 and what that does is it gives it an initial value of 3 to x.
Okay, so you could actually have the declaration of the variable without the initial value,
but you always need to give it an initial value before you use it, so a lot of times we just
give it the initial value when we actually declare it, okay.
If we want it to have something of type double, maybe something called Y, we could
have something called Double Y equals 5.2 and what that means is somewhere in
memory we have this thing called Y, which has value 5.2 in it, and it’s just a real value.
So the general form for how you do these declarations is you say type and I’ll put little
squiggles underneath these just to let you know that this is the general form, the name
and then potentially an equal and some initial value, followed by the semi colon, and
that’s how you do the declaration.
And so the question that comes up where do you actually make these declarations and the
place you generally at least for the time being make the declarations of value, for
declarations of variables is inside methods.
So when you create some method like you have public, void, run and you’re gonna put
everything that’s gonna go inside run in there, you could, for example, have this line in
there and this would create X with a value of 3 and Y with a value of 5.2 and you
wouldn’t have the general form there, but for example, you could have those declarations
inside run and what that means is you have those variables created with some values
available to you inside this method called run.
They’re only available to you inside that method called run. They’re not available to you
in some other method and we’ll talk about how you get values passed around between
different methods in a few days, but for the time being when you have your variables
they’re only available in that method. Okay, so any questions about that – variables or
values? Uh-huh?
Student:If you have them inside the public run method [inaudible], will that method be
able to take that variable?
Instructor (Mehran Sahami):Well, you won’t be defining another method inside run,
right; you’ll be defining another method that’s separate from run. It’s just a separate
method. It won’t be available in that separate method. It doesn’t matter if it’s public or
private. It just not available there. So this public or private thing that you have here
doesn’t affect the visibility of your variables. Your variables are always only visible
inside the method in which they’re declared and set up, okay?
Now, one other thing that we did when we sort of, you know, did this equals thing over
here, if we wanted to, we could have actually done this in two lines rather than setting up
X initial value there, we could have said into X and then we could have set X equals 3
over here and gotten the same effect.
And when we say X equals 3, this equals is not equals in mathematics; it’s actually
what’s known as an assignment statement in Java or in most programming languages.
And the idea is we’re taking some value over here. That’s what’s on the right-hand side
of the equals and assigning it to whatever variable is listed over on the left-hand side of
the equals, so we’re assigning that value, okay?
And so the general form for an assignment, let’s just do that over here, is pretty
straightforward, you just saw it, is variable and this is the name of the variable. So I’ll
squiggle – equals some value or some expression for a value and we’ll talk about
expressions in just a second with a semi colon at the end of it, and that’s how you assign
a value.
You can assign values multiple times to a variable, to a variable. It’s a variable, the
contents change. So you say, “Hey, X equals ,” and then down here somewhere, “Hey X
equals 4,” and when you get to this line up until you get to that line from here to here, X
will have had the value 3 and when it gets to this line, it’ll stick a 4 in the box. And that’s
perfectly fine because X is a variable. As long as everything you stick in there is of the
type of which X is declared, you’re okay, okay?
So what that also means is when you’re doing Assignment you can do things that are
perfectly fine in programming, but to mathematicians, they just go nuts; they go crazy
like veins just burst in your head and you hear these popping noises and people dying in
the streets, which is you can say, “Hey, I have some variable called total. Let me create
some variable in its total,” which I’ll give some initial value like 10 and that’s a good
time.
And then I say, “Hey total equals total plus 1.” And if you’re a mathematician, you look
at that and say, “No, man. Total can’t equal total plus 1. That’s just not right.” And then
you got this whole philosophical question about, you know, if this is like total is equal to
infinity and you’re just like, “No, no, no, that’s not what we’re talking about.”
We’re talking about assignment. This is into equals, this is an assignment. So what it says
is evaluate the right-hand side, okay? Total – what was total’s previous value. Go and
look it up in the box over here you have some box for total. Its value was 10. It looks it
up. It says, “Oh, that was 10.” I'm gonna add 1 to it, that gives me 11. What do I do with
that 11? Stick it back in the box named Total. So it just says okay, and it puts an 11 over
here and that’s perfectly fine.
So it’s perfectly fine to do something like then where you take the old value for a
variable, you do some manipulation on it, you stick it back in the same variable. Okay?
So with that said, now that you know about variables, we can go back to a couple of the
programs that you saw last time and things ill now begin to make a little bit more sense,
so if you come to the computer, remember our little friend, add two integers that you saw
last time.
Suddenly the world opens up a little bit and we say, yeah, add two integers is a console
program, right. So it’s gonna write some text out to a console somewhere and we have
our run method. We print out a line; we know that the method print [inaudible] when we
say that, whatever we put inside the double quotes gets printed to the screen so it prints
out this program adds two numbers, so we execute that line and after we execute it, it
writes it out and it comes to the next line.
Low and behold, what have we done here? We’ve declared a variable named N1. What’s
the value for that variable that we’re gonna assign to it? We’re going to call some
method. The method we’re gonna call is something called Read INT and this is a method
that’s provided for you in console programs. All console programs can do this. The way
it works is you give it some text between two double quotes. It writes that text on the
screen just like you saw last time and asks for input from the user.
Whatever value the user types in and hits enter, that number is the value that gets what
we call return by read INT. It’s the value that [inaudible]. It’s kind of giving it back to
you. Do what you want. What are you gonna do with it? You’re gonna assign it to the
Box N1, so here’s the box for N1.
We execute this statement. It’s coming; it’s gonna print to enter N1 on the screen. It’s
gonna ask us for a value. Let’s say we type in the value 17 and it sticks that 17 so this
expression over here evaluates the 17. It sticks 17 in the box for N1, goes to the next line,
now it declares N2. We have some box. Its initial value also is gonna come from the user
via this read INT method.
So we call read INT. It asks us for another value; we type in 25, and it sticks that in the
box. Now, we’re gonna declare another; we just declare until the cows come home, right?
Declaring is fun; it’s cheap. It’s easy; do it, do it often, right, so we’re gonna declare
another variable total, so we have another box over here for total and the value of total
that ‘s gonna get assigned there is just whatever value is in N1 plus N2.
So to evaluate this side, it says I need to look up the box N1, so at the point where it
reaches this line, it evaluates whatever is in N1. This isn’t some truth that holds for all
time. It’s just an assignment that it does when it reaches that line. So it says, find out
what’s in N1, add it to what’s in N2.
That’ll give you the value 42; stick that in Total, which is what you get. And the last line
says, I'm gonna print something to the screen where the total is and you see these funky
plusses and you’re like, “Whoa, whoa, whoa Meron, I thought plus was light lading
things together. What’s going on? You’re like trying to add – this thing’s got the value of
42. I know that because it’s in the box. You’re trying to add 42 to some text? That’s not
right.”
Well, in most worlds, it would not be right, but it turns out in the Java world it’s perfectly
fine and when it sees something that some words with a plus sign, this plus sign here is
not numerical addition anymore. This is essentially you can think of as a concatenation
operator. It says, “Take whatever text is here and add to that text, the textural form of this
value.”
Well, the textural form of 42 is just the Characters 4 and 2, so it sort of adds that 42 here
and then it adds to the end of that a little period, so it concatenates all those things
together and then prints them out and says the totals 42.
So any questions about the program? If you’re feeling good, like you understand what
just went on in the program, nod your head. Rock on. That’s what I like to see. All right.
So with that said, we can go back to something else we did last time, right, so now you
know how all this variables and assignments and types and you’re like, “Hey, Meron,
yeah, that’s all good and well, but last time you were telling me about like classes and
objects and drawing stuff on the screen like, what’s up with all that.”
And this is the time when we actually do sort of the, you know, Reese’s Peanut Butter
Cup. Like it’s two great tastes that taste great together. We take some objects over here
and some variables over here and we just slam them together, and now you’re going to
have variables that contain objects. They taste great, all right?
So here are some of the objects that you considered last time, right? We had things called,
like some classes. You have the G label class and the G –rect class and the G-oval class.
These are all these graphics classes like a label [inaudible] or rectangle or an oval. I’ll
show you examples of all these things this time.
And these guys were actually all classes that are part of a hierarchy of other classes and
the other classes, they’re all part of is G object? So what G-object is a G-object is a class.
Don’t let the name fool you. Some people see G-object and they think, “Oh, that must be
an object.” No, G-object is a class. It just means a graphics object. And guess what, a
rectangle or an oval or a line or a label or all different graphics objects. So what that
actually looks like in terms of the hierarchy just like you saw last time, is the classes are
represented, kind of like this in the hierarchy, all of these classes are actually G-objects.
Okay, they’re all sub classes of G-objects. It means they’re specializations. So any
behavior that G-object has, all of these things have, but they might have their own
specialized behavior, as well.
Now, the interesting thing about all this is that when you have classes and you create
objects, you can store those objects in a variable. You can say, “Give me a variable that is
a box,” and the type that that box holds is an object that’s the type of some class, so all
classes can actually be used as type means, okay?
Now, that’s kind of funky. Let me show you an example, okay? Here is another program
you saw last time. Now, we can just kind of reveal the mystery about variables. We have
this program, Hello program that extends the graphics program, right, so it’s gonna draw
us some pictures.
Well what are we actually doing on this first line? Hey, we’re doing a declaration and
assignments on the first line. What’s the type of our variable? It’s a G-label. So we use
the class name as the type. The name is label, so we have a box called label and what that
box is gonna hold is any object of the class G-label. Okay, so that’s the type. It’s gonna
hold any object.
And the question comes up, how do we get an object of type G label. And here’s the
funky part. The way we get an object of type G label is we have to ask for a new G-label.
So we give the name of the class here and class is depending on the class, you know, see
some examples of this will take in or give in some initial values for what we refer to as
parameters, and these parameters are all separated by commas. But at some initial values,
that this object uses to sort of set itself up. It initializes the objects.
So objects rather than just taking one value, can potentially hold multiple values in them.
In this case, the G-label is gonna have Hello World as some text that it’s gonna display in
some location that’s 100,75.
So we say, “Hey G-label, you’re the class. I don’t have an object of you yet. You’re the
class.” When I say, “Give me a new G label, it’s sort of like going to the factor. You sort
of show up at the G-label factory and you say, “Yo, G-label factory. Give me a new
object,” and G-label factory is sort of sitting up there and says, “Well, what kind of new
object do you want? Yeah, I can give you a new G-label, but how is that initial G label
going to look,” and you’re providing these parameters that sort of specify what the initial
G-label looks like.
So this line is now created a G-label, okay? And it has some initial, so when we execute
that line, it has some initial text that it’s gonna display and somewhere it’s also storing
the value is 175 because it knows where that’s gonna be on the screen.
Now, what we’re gonna do is we’re going to tell that object to do some additional stuff.
The way we tell an object to do something is we specify the name of the variable for the
object, okay. So the object name is label. That’s the name of the variable. And so that’s
what we say here. We don’t say G-label. We say the name of the variable label.
Then we have a dot; then we have the name of the method that we’re going to call for
that particular object. So it’s a little bit different than Karel’s world, all right. In Karel’s
world, every time you call the method, Karel was the one executing that particular
method.
Here when you have multiple objects, you need to specify which object you want to
execute this method. So you say, “Hey, label, yeah, I'm referring to you, buddy. Set your
fonts to be this particular font, san seraph which you saw last time.” It just makes it big. It
makes it 36-point font. And then you say, “Hey label, yeah, you, same guy, or gal or it or
whatever it may be. Set your color to be red.”
And it says, “Okay, I’ll set my color to be red, and then finally if I want to take this label
and stick it up onto my graphics canvas which is actually the program I'm looking at.
Right, I’ve done all this stuff and my program’s still bringing out a blank screen. It’s like
here you go, nothing going on here. I say add and the name of the object that I want to
add, right because now I'm holding this little object called label.
This is my little felt Hello World, and I want to say, “Hey take the felt hello world that’s
so cute and just stick it in the world,” so we add it to the graphics program, basically and
it shows up in the screen where it knows it’s supposed to show up at a 100,75.
So the general form for this, the people will refer to when you see something like this,
you have name of the variable and the method name and the Java-esc names that we give
to these, just so we hear other programmers refer to them, you know what they’re talking
about, is they say the object is the receiver. So the object here is the one who’s receiving
or being told to do something, okay?
So the name of the variable is the receiver and the method that’s being called is called the
message and so there’s this whole notion of sending messages, kind of like you could
think of programming as I am, right, and in your little I am you have like your friend,
Bob, and your friend, Sally and your friend, Dave, and your friend, Label, right. And
Label is just sitting there in I am and Label is not very talkative and once in awhile you
can send a message to I am which is a form of message that label understands and then
Label will do something.
So this is called the message that we send to the receiver, is kind of the nomenclature.
But a lot of times, you’ll just hear people say, I made a method call on the object and it
means exactly the same thing. Again, we like to give funky names to simple concepts.
Okay, so any questions about that, uh-huh?
Student:If you add the label first, then you start [inaudible].
Instructor (Mehran Sahami):Yeah, you can still, after you sort of put the little object up
there that says, “Oh, the object’s in the world, and say, “Object change your color to red,”
and that’s where it’s a lot cooler than the felt animals you had when you were a kid,
because it’ll just change to red right there on the screen because once it’s been added, it’s
up on your canvas, and now any messages that you send to it will actually change its
appearance on the canvas. Okay.
So with that said, let’s kind of go through and understand a little bit more about what are
some of these messages or methods that we can send to particular kinds of objects. So to
do that, first let’s talk about the graphics world that we live in. There’s a couple of things
you want to think about the graphics world.
How do we specify all these things like locations and how is it laid out. Well the origins,
the upper left, so the upper left corner of your graphics window is location 00. Every
thing in your graphics window is measured in pixels.
Pixels are the little dots on your screen, so if you get out a magnifying glass and you go
up to your monitor and you look real close and you get like eye strain and then you want
to sue, don’t worry. It’s just fine. At least you saw a pixel and it brought you al little
closer to Nirvana. So a pixel is just a little squares essentially on your screen that could
actually get displayed.
All the numbers that we refer to are in terms of pixels. So when we think about X and Y
coordinates, X is how far you go across, sort of across the screen and Y is how far you go
down. The X coordinates just increase to the right from 00 and the Y coordinates,
different than what you’re used to in mathematics, Y coordinates go down. So normally,
we think of this as a negative Y direction. Not so in Java’s world. This is the positive Y
direction going down.
Hey that’s just the way life is. It’s been like that since I was a wee tike, or actually, since
Java came around. Okay, and so you might wonder, “Hey, if I have some label, like Hello
World, and I specify some location, where is that really on this Hello World thing and so
the G-label coordinates, the coordinates that 100,75 that we gave it were the X and Y
location of the base line of the first character. So that first pixel right there on the lower
left hand corner of the H, okay? And so that’s 175. That’s how things were laid out. Uhhuh
Student:Is it possibly to specify [inaudible] using ratios?
Instructor (Mehran Sahami):Well, everything’s in terms of pixels. There’s some stuff
you’ll see later on in the class where we actually specify some things like in polar
coordinates if you’re familiar with polar coordinates, you’ll get to that later on.
But you want to think of these numbers as just being absolute pixels and you can do some
math to figure out where those pixels should actually be. But they’re still just pixels, just
way off.
All right, so remember all of these classes are organized in some hierarchy and
everything that we talked about, right, G-label, G rect, G-oval and G-line are all Gobjects,
which means any behavior that a G-object has, all of these puppies have. So let’s
start off by thinking about what are the behaviors or methods that are available on Gobjects.
So one is set color; you just saw an example of that, right, you specified the object, you
say set color and you give it some color and I’ll show you where the colors come from
and it sets the color of the specified object to the color you just specified as this thing
called a parameter. So the thing that’s inside the parentheses in our formal speak, we
refer to as parameter. So methods have parameters. They’re the values that you provide
inside the parentheses when you invoke a particular method, okay?
So there’s a single parameter there, color. There’s also something there called set
location, which takes an X and Y coordinates. Again X and Y are in pixels and it sets the
location of that object to that XY, so this method has two parameters, X and Y. And you
might say, “But Meron, when I created the G-label before, didn’t I specify the X and Y
location when I told the factory to give me one of these G-label objects?”
Yeah, you did, but you didn’t have to, and it turns out there’s times you don’t want to;
you want to just say, “Hey give me a label that’s got the words Hello World in it and later
on I’ll figure out where it’s actually gonna go on the screen, so I’ll specify what the X
and Y are,” but until you specify the X and Y, it doesn’t know, but you can specify after
you’ve created the object, is the important thing.
And move, and here’s the funky thing. You can actually tell an object, like you have your
little, you know, Hello World somewhere on the screen and it’s kind of like the furniture
idea of objects. You’re like, “Yeah, I don’t like how it looks there. Move it a little to the
right. And so there’s a move method and its coordinates if you’re sort of a Calculus
person or DX and DY, and if you’re not a Calculus person, don’t worry, you don’t need
to be a Calculus. This is the closest we get to Calculus in this class. Rock on.
DX and DY just means how many pixels in the X direction and the Y direction should
you move this object from its previous location and these can be positive or negative,
because you can actually have something negative say in the Y direction and it’ll move it
up on the screen.
So it’s just the offset or how much you want to, so think of it as the difference in X and
the difference in Y, how much do you want to change where it moved. Uh-huh, question?
Student:Do you use a set location XY and then [inaudible]?
Instructor (Mehran Sahami):Can you do set location and so you –
Student:[Inaudible] later define X and Y.
Instructor (Mehran Sahami):No, if you want to say set location XY, you’re referring to
two variables X and Y, so there’s variables X and Y and each have already been declared
and have values.
Student:[Inaudible].
Instructor (Mehran Sahami):Yeah, so anything that’s a parameter here, you can
actually use a variable rather than an actual value, like an actual number, and we’ll see
some examples of that as we go along. [Inaudible]. So where do all these colors come
from? It turns out these colors come from a standard library that someone in the Java
world wrote that’s called the Java AWT package, so if you want to use these colors at the
top of the program, and I’ll show you and example, that should say, importJava.AWT.star
and these are all the colors, so they’re all the name color, dot and then what the color
actually is.
So you just saw an example where we used colored dot red to make Hello World red, but
there’s all these different colors and they’re all in your book, so you don’t need to
scribble them down hurriedly, but you know, different shades or black or grey or white
and you know, magenta and sienna if you’re sort of a color photography sort of person,
but there’s a whole set of colors and you can just go to town on them. Okay.
So all G objects, all of these things respond to these methods because these guys are all
objects, so any of those three methods will work on any of these objects, of objects of any
of these types. But there are some additional behaviors, there are some additional
methods that some of the specialized classes, the sub classes actually implement.
So G-label has some additional things that it does beyond just what a G-Object in general
would do. And the big one, well first of all, it’s got what we refer to as the constructor.
You can think of the constructor and I'm gonna do a little violence to the term, but you
can think of the constructor as a factory, okay? What the constructor says is, “Hey, I want
a new one of these guys,” so I use the word new and then I specify the constructor, okay?
The constructor is the name of the class of which you’re going to get a new object and
then some initial parameters. So the initial perimeters for a G-label for example, could be
what you just saw, the text that you wanted to display and its initial X and Y coordinate,
okay.
There’s some other ones. For example, you can change the fonts, right, it makes sense for
a label. It doesn’t make sense for a square or rectangle, to say, “Hey, square, you’re
font’s gonna be Helvetica.” And the square is like, “I'm four lines, man, I don’t have a
font. What are you talking about?” That’s why the notion of setting a font isn’t something
that all G-objects have. It’s only something that G-labels have which means the G-rect
and G-oval and G-line don’t have a set font.
This is just something that you can do with a G-label and what it does it says specify the
font that you want that label to show up in on the screen, and the general form for
specifying the font – this is all in your book and it shows you examples of the fonts, but
the general form is inside double quotes, because you’re gonna give it as a piece of text,
you specify the family of the font.
That would be something like times or Helvetica. The style of the font, which is, you
know, plain or bold or italic or bold or italic, so yeah, now in fact you can do all those
funky things your word processor does and then the size of your font, how big or small
you actually want it to be and you specify that as some texts and that would be what you
send over to this sent font method to set the text.
Okay, so any questions about that? Uh-huh?
Student:[Inaudible].
Instructor (Mehran Sahami):No, you get them all through graphics program. Rock on.
All right, so how do we draw some geometrical objects? Have another question?
Student:[Inaudible].
Instructor (Mehran Sahami):If you’re doing a graphics program without any colors,
you don’t need Java.awt.
Student:But if we’re doing one with color, then we need Java.awt in addition?
Instructor (Mehran Sahami):Yeah, in addition to a graphics program, and I‘ll give you
an example of that in just a second. I have to show you a program that has it.
So drawing geometrical objects – it turns out some of these other guys have funky things
that you can do specifically with them. So first of all, there’s the constructors, the
factories from which you can build new things. So how do I make a new rectangle? I say,
“Hey, I want a new G-rect.” I specify the X and Y location. It’s the upper left-hand
corner of that rectangle and then I specify the width and height of that rectangle in pixels.
Okay. So that’s the basic idea is upper left-hand corner and then width and height of the
rectangle.
Similarly, for oval – ovals are kind of funky because you look at this and you’re like,
“Hey I have an X and Y and I have a height. I didn’t like –width and height like ovals. I
thought an oval was defined by like two [inaudible] and that whole thing where you have
a string. Did you ever do that – you stick the two like nails in the board and you put the
string around it and you draw anyone? There’s like two people – yeah, like sorry.
Do it; go get a piece of wood, stick two nails in it, put some string around it and go get a
pencil, something you can draw ovals and you can draw a 1 and if you’re like 6 years old,
you’ll draw like 1,000, and if you’re 18, and draw one, you’re like, “Yeah, that was just
stupid.”
But the basic idea behind an oval is the reason why we specify this way is you specify
sort of an imaginary rectangle for the oval and the oval shows up as an oval that just
happens to touch the sides of the rectangle, which is how we sort of specify how wide
and broad it is.
So think imaginary rectangle and sort of the four ends of the oval would sort of be
touching it, and I’ll show you that momentarily. G line is very straightforward. G-line,
the way we specify line just like you know, the days of yore with Euclid, line is defined
by two points, right, that’s an infinite line, but we can think of where it ends at the two
points. So we specify an initial XY location and an ending XY location and it will just
draw a line between those two points, pretty straightforward. Uh-huh?
Student:[Inaudible] is the set location defined as the lower left corner of your object, and
the G-rectangle [inaudible] left corner?
Instructor (Mehran Sahami):Well, for set location is the lower left corner of for
textural objects, and then it becomes different for rectangles and ovals and stuff like that,
yeah. So it’s a slight variation because that’s just because we’re trying to deal with, you
know, texts and rectangles symmetrically and it’s tough to do, okay.
There’s also some additional methods that are just shared by G rect and G-oval. They
don’t actually apply to lines or to labels for that sense, rectangles and ovals can be filled,
so they can either be an outline. You can either have a rectangle that looks just like this
which is an outline or it can be filled in which means it’s just a big solid chunk of stuff.
So you said if it’s filled, you say this is either true or false with the actual word true or
false.
So if you’ve set it to true, then when you draw it on there, you say, “Hey, put this thing
up on my canvas.” By adding it to the canvas, it will show up filled in; it will show up
solid. And if this is set to false, it just shows up as the outline of the object, whether or
not that’s an oval or a rectangle.
And almost done here. There’s also a notion of a set fill color, and you might be
wondering, you’re like, “But Meron, you told me that set color. Here’s where things get a
little funky, you told me that set color is something that was defined for a G-object, so if
set color is defined over here, doesn’t that mean that a G-rect and a G oval already can set
that color?”
Yes, that’s true. “So what’s the set fill color all about?” And this is a slight variation.
When you set color for something, you set the color for the whole thing if that’s solid or
if it’s an outline, you’re setting the color for the whole thing.
When you set fill color, you are just setting the color for this internal portion. So imagine
like this was your rectangle, what color used to fill it in can actually be different than
what color the line is. So if you want the line, say, to be black and you want the fill to be
red, you can actually do that by setting the fill color to be red and then the outline is still
whatever color the actual outline was if you want to do that.
Okay, so if the color – if the interior is fill, so the set fill has to be true, then you can set
the fill color to be different. That’s a minor thing, but it’s kind of fun if you’re drawing
stuff, okay? So any questions about that? Oh, wait – we have a question over there, uhhuh.
Student:[Inaudible].
Instructor (Mehran Sahami):Oh, in the place of this word fill?
Student:Yeah.
Instructor (Mehran Sahami):It’s either the word true or the word false. So if you say
true, set filled is true which means it will be a solid thing; it will be filled in. Uh-huh?
Student:If your when you’re using the [inaudible], you specify a [inaudible], what is the
why would you use the set location [inaudible].
Instructor (Mehran Sahami):Maybe you wanna do some animation. Say like you have
like your bunny in the world and he’s gonna want to move along.
Student:[Inaudible].
Instructor (Mehran Sahami):Well, it’s set somewhere to begin with and then later on,
guess what you’re actually gonna be doing a program that involves animation. Rock on.
And you will move things around. So that’s where it comes from. All righty.
So one last thing that might be useful to you, sometimes you want to say, center
something in the graphics window or draw something in the bottom, how do you know
how big the graphics window actually is.
There’s two methods from the graphics program class, so these methods you might notice
they don’t have any objects, that is their receiver, and the reason for that is that both of
these methods, their receiver is the graphics program, so if you don’t specify the receiver
for a method, the thing that is actually receiving the method is the encapsulating class.
Okay, just like in Karel, when you had Karel and you said move and you didn’t specify
an object for the move, the move is going into Karel, so get width and get height. We’ll
return to you the width and the height of the graphics window in pixels.
So these actually give you back a numeric value that you can, for example, assign to a
variable and then do manipulations on it. Uh huh.
Student:If you don’t fill in [inaudible] something like set color to change the entire
background of the graphics [inaudible]?
Instructor (Mehran Sahami):Well, you can make the huge rectangle the size of the
graphics window and set it to be filled and set it to be a color and then you can change the
whole background that way. Uh-huh?
Student:Can you then change the size of the graphics window?
Instructor (Mehran Sahami):There is some stuff for later on, but for right now, just
think of a fixed size graphics window. Yeah, so let me push on just a little bit if we can
because what I want to actually show you now is a graphics window that makes, or a
graphics program that makes use or a bunch of this stuff so over here, here’s a little
program called fun graphics, okay.
And so we have a comment up at the top and here are all the imports you need. Notice I
[inaudible] for you. We need acm.graphicstar because we’re gonna write a graphics
program. We need acm.program.star because all programs that you write in this class are
gonna need that. And because we’re gonna use colors we additionally need Java.awt.star.
If we weren’t gonna use colors, we wouldn’t need that, but it’s needed for the colors. Uhhuh.
Student:[Inaudible].
Instructor (Mehran Sahami):It did; it might have just been hidden because sometimes it
just appears hidden until you expand it out, but it actually had it in there. So here’s what
we’re gonna do. Let me just run this program, show you what it displays on the screen
and then show you how we actually get that display, so it’s just like, “Hey Meron, you’re
just drawing garbage on my screen,” no, there’s really like a method to this madness. Not
really, there are multiple methods to this madness [inaudible].
I know, sometimes computer scientists should not be – that was actually not a canned
joke. That just came tome – how horrible is that? So here is what’s going on. We drew a
bunch of stuff on that screen, how did it get there. Well, hey Hello World; we probably
knew how that got there. This should all be familiar to you now. We got a new G-label.
We had some variable called label that we assigned it in. We set its font. We set its color
to red. Because we set its color to red, that’s why we need www.Java.awt because we’re
using colors.
We set its color to red and we said, “Hey, I got Hello World, throw it up on the screen,”
so we add label. You give it the name of the variable and there it appears.
Over here we say, “Hey G-rect. I want a new rectangle that’s upper left-hand coordinate
is 10,10 and it’s size is gonna be 50,50, which means it is a square. It’s not filled in. I
haven’t specified its color right,” so if you don’t say set fill, it’s not automatically filled
in. If you don’t specify the color to automatically black and then I add it and then you get
that little box all the way up in the upper left-hand corner.
Then, I say, “Hey, you know what, I want some other G-rect because it’s cooler.” It’s
gonna have colors and it’s gonna be bigger and better and it’s gonna be nationwide, and
so what it’s gonna do is I'm gonna have rect 2 which is another variable of Type G-rect.
It’s perfectly fine for me to have multiple objects of the same type which they knew Grect
that’s upper left-hand coordinates is 300,75 and whose size is honking – it’s 200 by
100, so it’s big long thing, and it’s gonna be filled in and I'm gonna set its fill color to be
red, so the whole thing is red, throw it up there and so what I get is that big, rectangle.
Just ignore the big oval one in front of it for now; I get this big red rectangle up there.
And I say, “Well, that’s kind of cool, but I want to see what this oval thing is all about.
So Hey, Meron, make me an oval.” And I'm like, “All right, well, G-oval will make you
an oval,” and the dimensions of the oval, its upper left-hand coordinate and its size are
exactly the same as the rectangle, and the reason for doing that is to show you the oval in
relation to the rectangle that you specified.
It’s set filled is true and it’s set fill color, not its set color, but its set fill color is set to be
green, which means the internal dividend will be green, the outline of the oval will still be
black, because we did not set its color and then we added and there you get that green
oval and you can notice its four ends touch the same four ends as this rectangle and if you
look real closely there’s actually a green line that demarcates the oval and then the
middle fill is actually green.
It might be a little hard to see, but that’s the case. Then we also have a line, so I will just
call this my funky line, and my funky line is a line that starts at 100,150 and it extends to
the location 200,175 and there is my funky line. Yeah, it’s a funky line.
All right, and then I add another thing and you’re like, “Dude where’s my line.” And so
Dude where is my line is a line that should cut across the entire graphics window because
it starts at 00, well not the entire graphics window. It starts at 00 in the upper left-hand
corner and goes to 100,100, and this is a common error which is why I how it to you.
You look up there and you’re like, “But Meron, there’s only one line,” and that’s your
funky line or my funky line as the case may be. Where is Dude where is my line? And
it’s not up there. Why is it not up there?
Student:[Inaudible].
Instructor (Mehran Sahami):Yeah. You did not add it to the graphics content, okay.
Common error – people will go ahead and create something and add all the colors and set
all the sides and be like, “Ah, I'm rocking,” and then they’ll run their program and
nothing shows up and they start tearing their hair out and beating their section leader and
it’s a bad time, and they’re sitting there contemplating life in jail and then they realize, “I
just should have added it to the canvas, all right.”
But you can’t give that as an excuse to the judge. All right. So any questions about that?
All right. Let me very quickly – I need to push on real quickly. So I want to tell you a
little bit about expressions before we finish up and we’ll do more expressions, but you
need to know some basic stuff on expressions.
So all an expression is is you already saw one. And expression is something like INT
total, equals N1 plus N2. This is an expression. It’s just some mathematical expression
that tells us how things kind of relate to each other.
And basically all an expression is it’s a bunch of terms and these terms can be either
individual variables or they can be constant values, like they ca be like the Number 2 or 3
or they could be some method called like Read INT that actually gets a value from the
user, for example, and there’s some operators between them, like the addition operator,
and so when you take some terms and you put operators between them to combine the
terms that’s called an expression, all right.
Fairly straightforward stuff – you’ve probably seen these. There’s a bunch of operators
you should know about. The operators are things like plus, minus, times, which is
actually a star or asterisk, which is how we refer to times. It’s not as X – division and
then strangely enough, this thing’s that looks like percent and it’s not the percentage
operator, although you might think that. This is what’s known as the remainder operator,
okay.
So these puppies generally work like you would think, add two numbers, subtract two
numbers. There’s also a uniary minus. The uniary minus is the funky mathematical way
of saying negative sign. So you could actually say like equals negative N1 plus N2.
That’s like a negative minus. That’s perfectly fine. Okay, or you can use that same thing,
you know, as subtraction if it’s between two terms.
Multiplication, division, the thing about division that is funky is it depends on how
division is used, okay and I’ll tell you a little bit more about that next time, but I want to
talk about remainder right now.
And remember back in second grade, when you did like short division and you said, “Oh,
I had 5 and 2 – how many times does 2 go into 5 – 2 and you were like remainder 1.
Anyone remember that? Wasn’t that such good time? I loved remainder – like that’s the
online like math. I'm like – and when the remainder was 0, I got pissed.
But that’s what remainder was all about. It’s just what’s left after you do the division. So
that’s the way you should think about percentage. It’s the remainder operator, and you’re
like, “So how does that work?” So what that means is if I say 7 remainder 2, the value of
this is 1 because it’s after I divide 7 by 2 and I see how many whole times 2 goes into 7,
what’s the remainder, it’s 1, okay? You could say something funky, like, hey what’s 7
remainder 20? You’re like well, 20 doesn’t go into 7, Meron. So that would be 0
remainder – rock on.
So that’s the way it works. It’s not the modulus operator. If you’re a mathematician, or if
you’ve worked with other languages and you’ve seen clusters and you’re like, “Oh, that’s
the modular operator.”
It’s not in Java; it’s remainder an dif you try to apply it to negative numbers, unexpected
things, what’s not unexpected; it’s just not what you would have expected in the
mathematical sense. So as far as you see it in the book and everything we do in this class,
just apply it to positive integers and you can only apply it to integers so there’s no
remainder with valued doubles, there’s no remainder.
And so when we come back next time we’ll talk a little bit about some of these
expressions. Any questions before we break? All right, and I’ll see you – oh, there’s a
question. Why don’t you just come up and ask it. Thank you.
[End of Audio]
Duration: 52 minutes

Search This Blog