Download CMPT 101/4 : Week 2 1. VARIABLES AND ASSIGNMENT

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CMPT 101/4 : Week 2
1. VARIABLES AND ASSIGNMENT STATEMENTS
A variable is an identifier that can be assigned a value (integer, real, string,
object). This identifier is also associated with one or more memory cells where the
value is stored.
The rules for naming variables are simple:
• The identifier cannot be a reserved word. Reserved words are
described on page705 of "Problem Solving with Java" , by Koffman.
A similar table will be available at the course website.
• The identifier must begin with a letter. Subsequent characters can be
letters, digits, "underscore", or "$". Conventions on constructing
variable names are described in Appendix A1 of Horstmann.
It is the programmer’s repsonsibility to define what type of value is to be stored
in an identifier. This is achieved with a declaration statement:
• Integers are declared with the word int preceding the the initial use
of the identifier.
• Real numbers are declared with the word double preceding the
initial use of the identifier.
• Strings are declared with the word String preceding the initial use
of the identifier. Note the capital letter on String.
• Objects are declared with the class name preceding the initial use of
the identifier.
For example:
double x;
int largest;
Rectangle r1;
Declaration statements only identify variables and indicate the type of value they
will hold. An assignment statement is required to assign a value to any variable.
An assignment statement is a (possibly initially declared) variable followed by an
"=" sign, followed by an expression that evaluates to a value that has the same type
as the identifier. Some examples:
1. double x; This statement is not an assignment statement. It
simply declares that x is to have a real number as its value, but no
value has been assigned.
(C) A.H.Dixon
page..11
2. String course = "CMPT 101"; This assignment statement
declares that course is to have a String as it value, and assigns
the string CMPT 101 as the initial value of that string.
3. Rectangle box = new Rectangle(10, 25, 13, 18);
This assignment statement declares that box is to have a
Rectangle object as its value and is initially assigned a value
corresponding to a rectangle with top-left corner at coordinates
(10,25) and of width 13, and height 18.
Example: The following program illustrates a possible way to analyze a
problem for the important elements before writing a program to solve it. The
principal idea is to try and identify the objects that will be required and what
messages these objects will need to receive.
The problem is to design a program that compares a message entered by a user
on the keyboard, with a "secret message" that is represented internally in the
program. If the entry matches the message, then an acknowledgement is displayed
on the monitor; otherwise the lack of a match is displayed.
1. The first step is to identify the objects required for the solution. In
this case the following objects will be needed:
• A "monitor" object to display messages. (for example,
System.out).
• A "keyboard" object to enter messages.
object System.in is such an object)
(The pre-defined
• An "interpreter" object that can transform keyboard messages
into ones that are represented by strings. (The predefined class
ConsoleReader defines objects of this type. We will use it
to construct an object called input.
2. Using these objects the messages that the program will need to use
are:
// To request a message from the user:
System.out.print("Enter your guess: ");
// To indicate a matching message:
System.out.println("Good guess!");
// To indicate a mismatch:
System.out.println("Sorry, no match.");
// To retrieve a String from the
// keyboard and assign it an identifier:
String answer = input.readLine();
3. However, before we can use an object called input we need to
create it; that is, we need to create a ConsoleReader object and
(C) A.H.Dixon
page..12
assign it to the identifier input:
ConsoleReader input =
new ConsoleReader(System.in);
4. Finally we need to compare two String values and choose one of two
alternatives. Strings have methods that allow them to be
compared with other Stringts.
In particular the method
equals("CMPT 101/4") compares the string Regis Filbin
with the string variable answer using the following message:
answer.equals("Regis Filbin")
This expression is an example of a predicate; that is, an expression
whose value is true or false. Predicates form part of a java statement
called an IF statement that permits one to choose between two
alternatives:
if (predicate)
statement to perform if predicate is true;
else
statement to perform if predicate is false;
Notice the parentheses around the predicate.
For the example program the following IF statement is required:
if (answer.equals("CMPT 101/4"))
System.out.println("Good guess!");
else
System.out.println("Sorry, no match.");
All the parts can now be placed into a Java program:
public class Example2
{ public static void main( String[] args)
{ ConsoleReader input =
new ConsoleReader(System.in);
// request a message from the user:
System.out.print("Enter your guess: ");
String answer = input.readLine();
if (answer.equals("CMPT 101/4"))
System.out.println("Good guess!");
else
System.out.println("Sorry, no match.");
}
}
2. ASSIGNMENT STATEMENTS
As described in the previous section, values are assigned to variables with
assignment statements. The formal syntax of an assignment statement is:
[<datatype or class>] <identifier> = <expression>
The notation used to define the statement is called BNF or Bachus-Naur Form
notation. The symbols "<" and ">" enclose an element description. In an actual
(C) A.H.Dixon
page..13
assignment statement, they would be replace by specific items as described. For
example <identifier> would be replaced by a valid Java variable name. The
symbols "[" and "]" enclose anything that is optional; that is, not required in every
statement. In this a <datatype or class> is not required in every
assignment statement.
As mentioned previously, variables need to be declared, and this can be achieved
with a declaration statement. However, since variables are not usually introduced
into a program until they are required, the declaration statement is usually
combined with an assignment statement to initialize the variable to a value. For
example:
double radius = 1.25;
double area = 3.14159 * radius * radius;
int largest = 10000;
Thus, a <datatype or class> can be provided with a declaration
statement or with an assignment statement. In either case, it can occur only once,
when the variable is initially defined.
In assignment statements, any of following can be an <expression>:
• a constant,
• a variable,
• a newly created object,
• an algebraic expression,
• a method call,
• a composition of methods,
• a cascade of methods,
• a combination of the above
In order to analyze the effect of an assignment statement, is important to
understand how different types of <expression>s are evaluated. The following
describes the evaluation process in more detail.
2.1. NUMERIC EXPRESSIONS
Since there are two types of numbers, int and double, the value of an
assignment statement can also be either int or double. If all values and
variables have the same type then that is the type of the result.
(C) A.H.Dixon
page..14
When the types are mixed in an expression, then the type of the resulting value is
always double, and this should be the type of the variable where the result is to be
stored:
int sum = 1 + 2 + 3 + 4;
double sum = 1. + 2. + 3. + 4.
double sum = 1 + 2. + 3 + 4.
Complex algebraic expressions can be constructed from variables, values, and
five binary arithmetic operations. They are:
• addition: +
• subtraction: • multiplication: *
• division: /
• modulus (remainder): %
Generally it is desirable to use parentheses to control the order in which the
arithmetic operations are performed. However when an expression does not
completely define the order of evaluation using parentheses, the rules of
precedence must be applied:
1. Expressions inside parentheses are evaluated first.
Nested
parentheses are evaluated from the innermost set to the outermost set.
2. Unary minus is performed next.
3. The operations *, /, % (multiplication, division, remainder) are
performed next, proceeding from left-to-right.
4. The operations +, - (addition, subtraction} are performed next.
Again, if there is more than one, evaluation proceeds from left to
right.
A convenient way of analyzing the evaluation of expressions using the rules of
precedence is to construct an evaluation tree. The evaluation tree graphically
illustrates the order in which the operators are evaluated in an expression. This is
conveyed by the position of the node (circle) labelled by an operator. The closer to
the top of the page is a node, the earlier it is evaluated in the expression. The
evaluation trees for two examples are given in the diagrams on the next page.
(C) A.H.Dixon
page..15
double area =
3.14159
*
radius
*
radius
*
*
int n =
x
*
y
*
2
+
a
/
b
*
*
/
+
In these examples, the leftmost "*" is evaluated first. In the top example, the
rightmost "*" is evaluated last, while in the bottom example, the "+" symbol is
evaluated last.
(C) A.H.Dixon
page..16
2.2. CASCADES AND COMPOSITIONS
A message is passed to a receiver by specifying a method and possibly some
additional details. The result of passing that message may produce a value which
can then be assigned an identifier (using an assignment statement). Alternatively
the result can become the receiver of another message.
As a result, a Java statement may consist of a sequence of messages being
applied to objects that are a consequence of other messages.
For example the following statements create the string "abc":
String c1 = "a";
String c2 = "b";
String c3 = "c";
String y = c1.concat(c2);
y = y.concat(c3);
Note that only one message is sent to a receiver in each statement. Alternatively,
one could achieve the same result with a single statement:
String y = c1.concat(c2).concat(c3);
In this case there are two messages, and it is important to evaluate the righthand
side in the appropriate order. The steps taken are as follows:
1. concat(c2) message sent to object c1. This message creates a
new String object, called the reference object.
2. concat(c3) message sent to the reference object from step (1),
creating another new object; that is, a second reference object.
3. The second reference object is assigned to the identifier y.
In other words, the order of "message sending" is left-to-right. When message
passing occurs in this order the evaluation steps define a cascade.
Another way in which the String "abc" could have been obtained using one
message per statement is as follows:
String y = c2.concat(c3);
y = c1.concat(y);
In this case the substring "bc" is constructed first and then "a" is added to the
front. A similar result can also be achieved with the following statement:
String y = c1.concat(c2.concat(c3));
The steps taken to evaluate the righthand side are as follows:
1. concat(c3) message sent to c2 creating a reference object.
2. The reference object provides additional details for a second message
concat(<reference>.
(C) A.H.Dixon
page..17
3. The second message sent to c1 creates a second reference object
which is then assigned to the identifier y;
In this case the evaluation is proceeding right-to-left. When message passing
occurs in this order the evaluation steps define a composition.
In evaluating expressions where more than a single message is defined it is
important to determine the order of evaluation. It is also possible for an expression
to exhibit both cascades and compositions.
Cascades and compositions of the same method occur frequently in many
contexts. In the case of Strings, the concat method is used frequently to build
longer Strings from shorter ones. This results in cascades of the concat
method as the previous example of a cascade illustrates. For this reason, the
concat method is also represented by the symbol "+" and an alternative syntax
available for defining cascades of concats. The previous example of a cascade
can now be written as:
String y = c1 + c2 + c3;
instead of
String y = c1.concat(c2).concat(c3);
(C) A.H.Dixon
page..18