T u t o

advertisement
Tutorial 2
Topics
Control Structures
o Conditional statement
o Iteration
Classes
o Define a class
o Instantiate a class
o Static fields
Tutorial Problems
Design Problem
Basic Control Structures
There are two basic control structures
Conditional statements: if … else…
Iteration:
while loop, do … while loop, and for loop
Conditional Statement
The general form of an if statement is:
if(expression)
statement1
else
statement2
next statement
If the expression is true, statement1 gets executed. If it is false, statement2 gets
executed. For example:
if (grade >= 90)
System.out.println("Yeah I got an A!");
else
System.out.println("So I got a B!");
System.out.println (“Always printed”);
Iteration Structure
Sometimes, you need to repeat the same statements multiple times. In that case, you
need to use the iteration structure. There are two kinds of iteration structure:
indeterminate loops and determinate loops.
In an indeterminate loop, you don’t know how many times a loop will be executed.
Therefore, you need the help of a Boolean expression:
while (expression) {
statements;
………………….
}
The statements will be executed repeatedly as long as the expression is true. Here is
an example:
Grade = 0;
while (Grade <= 90) {
System.out.println("Work harder!");
Grade += 10;
}
System.out.println("Great job!");
Here, the message "Work harder!" is printed 10 times while your grade progresses from
0 to 90. Only then will you see the message “Great job!”.
A variant of the while loop is the do-while structure. Instead of testing the expression
at the beginning of the loop, a do-while structure tests the expression at the end of
the loop. The general form of the do-while structure is:
do
statement
while (expression);
next statement
Here is the do-while flow chart for the above example.
If you want to control how many times the statements will be executed (“determinate
loop”), you need to use the for loop. In a for loop, you set up a counter which is
updated after every iteration. The loop will exit when the counter reaches its
limit. Here is an example:
for(grade = 0; grade <= 90; grade+=10) {
System.out.println("Work harder!");
}
System.out.println("Good job!");
Here, grade is initialized to 0. At every iteration, we add 10 points to the grade. When
it reaches 90, the loop terminates and control is passed to the next statement. As you
can see from the flow chart below, the for loop does the same thing as the while loop.
Classes
A class provides the definition of an object. Each class contains:
Variables (or fields): attributes of the object.
Methods: actions that the object can execute.
For example, we can define a Box class, which contains three attributes: width,
height, and length. It also contains three methods setWidth, setHeight, and setLength
which users can use to set the width, height, and length of a Box object.
Define a class
public class Box {
//Attributes
private double width;
private double height;
private double length;
//Methods
setWidth (double w);
setHeight (double h);
setLength (double l);
}
Each variable has a
Access identifier. A variable can be public or private (there are other access
identifiers we will cover later in the term.) In this example, all variables of the class
Box were declared private, implying that they can only be accessed within the class. A
public variable, on the other hand, can be accessed by anyone, both inside and
outside of the class.
Data type. A variable may be a simple data type like int and double, or another class.
Name. A variable name must begin with a letter, is case sensitive, and cannot be a
Java reserved word. A good practice is to use descriptive names, e.g. height rather
than h
For example, in the Box class, height is a private variable of the type double
We will talk about method definitions in the next session; they also have access
specifiers and other characteristics.
Instantiate a class
Once you have defined a class, you can create instances of that class. Each instance
has the same set of variables but different values. Here, we would like to create an
instance called myFirstBox:
Box myFirstBox = new Box();
Note that myFirstBox is not an object; it is a reference to the object which is created
when the new operator is called. The new operator invokes the class constructor (a
special method called when an object is first created) and allocates memory for the
object. (We will cover constructor in detail next tutorial).
The following example is a visual explanation of the difference between object and
object reference. Here, we defined two variables: a primitive data variable (int j) and
an object variable (Integer i) Both contains the integer value 2. Here we use square to
represent the primitive data type and box to represent the object.
int j = 2;
Integer i = new Integer(2);
As you can see from the above picture, the primitive variable j contains the value 2.
The object variable, i, however, does not contain the Integer object, but a reference
to the Integer object which has a value of 2.
So what happens when we assign i to another Integer object? Can you explain it using
the same box-and-square representation?
int k = j;
Integer m = i;
Static fields
Each object instance contains its own set of member variables and methods. Changes
made in one instance will not affect other instances. The only exception is static fields
and static methods.
If you define a field as static, there is only one such field per class. Lets look at the
following example:
public class Box {
//Attributes
static int numberOfBoxes = 0;
private double width;
……………………………
}
If we create 1,000 instances of Box, each box object would have its own width, but
there is only one numberOfBoxes for the class.
Since static fields belong to the class, they are referred to by using the class name,
not the instance name. For example:
public static void main (String args[]) {
Box b = new Box();
System.out.println(b.getWidth());
System.out.println(Box.numberOfBoxes());
}
Tutorial Problems
1.
for-loop
What is the output of following program?
for (int i = 1; i < 4; i++) {
for (int j = 1; j < 3; j++) {
System.out.println("i = " + i + " + j = " + j + "\n" );
}
}
Answer:
2.
do-while loop
Write a small program that prints out the even integers from 2 to 100 using a do while loop:
int counter = 2;
do
{
} while (____________________);
3.
for loop
Try to do the same thing using the for loop.
for (________; ________; _______)
_______________________________________;
4.
Class
Identify the compilation errors in the following program:
public class Box {
private double width;
private double height;
private double length;
}
public class TestBox {
public static void main (String argv[]) {
Box b1 = new Box();
b1.width = 5;
System.out.println(b1.width);
}
}
Answer:
5.
Write a Java program that calculates the factorial (n!) of a non-negative integer
n. Here is the formula
factorial (n) = 1
if n < 2,
n * (n - 1) * ... * 1 otherwise
Design Problem
Define a set of classes, with their member variables, to model MIT courses. Here is a
brief description:
Each MIT course has a course number, class room, instructor, and 2 TAs
Each TA has a name and email
Each instructor has a name, title (professor, associate professor, etc.), phone number,
and office number
Each class room has a room number and capacity
After defining the classes, please create an instance that describes 1.00. (You can get
all the relevant information from the course syllabus and only include 2 students - you
and your teammate - in the instance.
Download