Download Control Statements: Part I

Document related concepts
no text concepts found
Transcript
1
JAVA REVIEW: II
CISC6795, Xiaolan Zhang, Fordham University
Outline
2

Read input from users
 Use


packages
Variable, primitive types, expressions
Pseudocode, control structure
 Sequence
 Selection
statement
 Repetition statement
1
// Fig. 2.7: Addition.java
2
// Addition program that displays the sum of two numbers.
3
import java.util.Scanner; // program uses class Scanner
import declaration imports class
Scanner from package

java.util.
4
5
public class Addition
6
{
Outline
3
7
// main method begins execution of Java application
8
public static void main( String args[] )
9
{
Declare and initialize
 (1 variable
of 2)
input, which is a Scanner.
import
10
// create Scanner to obtain input from command window
11
Scanner input = new Scanner( System.in );
12
13
int number1; // first number to add
14
int number2; // second number to add
15
int sum; // sum of number1 and number2
Addition.
java
declaration

Scanner

nextInt
16
17
System.out.print( "Enter first integer: " ); // prompt
18
number1 = input.nextInt(); // read first number from user
19
Read an integer from the user
and assign it to number1.
Outline
4
20
System.out.print( "Enter second integer: " ); // prompt
21
number2 = input.nextInt(); // read second number from
Readuser
an integer
22
23
sum = number1 + number2; // add numbers
from the
user and assign it to
number2.  Additio
n.java
24
25
System.out.printf( "Sum is %d\n", sum ); // display sum

26
27


} // end method main
28
(2 of 2)
4. Addition
5. printf
Display the sum using
formatted output.
29 } // end class Addition
Enter first integer: 45
Enter second integer: 72
Sum is 117
Two integers entered by the
user.
Import Declaration
5
3

import java.util.Scanner;
// program uses class Scanner
Tell compiler to load class Scanner from java.util
package
Package: a named collection of related classes
 Must appear before first class declaration


Alternatively, import java.util package



import java.util.*;
Forgetting to “import” a class/package => compilation
error such as “cannot resolve symbol.”
By default, package java.lang is imported in every
Java program

only package in Java API that does not require an import
declaration.
Variable declaration statement
6
10
11
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );
Same as
Scanner input;
input = new Scanner (System.in);

Variables declaration
VariableType VariableName;
 A variable is a location in memory that stores a value, must be declared
before used
 Variable
name: any valid identifier (recall the rule?)
 Initialize variable in its declaration


Equal sign stands for assignment operator
The parameter System.in refers to standard input object (often links to
keyboard): input variable will be used to read inputs from keyboard
Primitive types
13
14
15
7
int number1; // first number to add
int number2; // second number to add
int sum; // second number to add
Declare variable number1, number2 and sum of type
int
 Primitive types in Java: int, float, double, char,
byte, boolean




int holds integer values (whole numbers): i.e., 0, -4, 97
Types float and double hold decimal numbers
Type char holds a single character: i.e., x, $, \n, 7
int number1, // first number to add
number2, // second number to add
sum; // second number to add


Can declare multiple variables of the same type in one declaration
Use comma-separated list
Primitive Types
8


Java requires all variables to have a type.
Primitive types in Java are portable across all
platforms.


Same size across all platforms, int is always 23 bits, …
Local variables of types char, byte, short, int, long,
float and double, i.e., those declared in a method
Are not initialized by default
 Using a variable without initializing it => compilation
error

Good Programming Practice
9



Declare each variable on a separate line
 allows a descriptive comment to be easily inserted
next to each declaration.
Choose meaningful variable names
 self-documenting program
Convention for variable-name identifiers
 begin with a lowercase letter, and every subsequent
word in the name begins with a capital letter
 e.g., firstNumber, studentRecord, …
Reading from keyboard
10
18
number1 = input.nextInt(); // read first number from user
 Result
of call to nextInt given to number1 using
assignment operator =
 Assignment
statement
 = binary operator - takes two operands


Expression on right evaluated and assigned to variable on left
Place spaces on both side of binary operator for more readable
code
 Read
as: number1 gets the value of
input.nextInt()
 How
to read double, char, …?
 Online
Java API document for the version of Java you use
 Examples used through the class are for Java SE 6
Adding Integers
11
23
sum = number1 + number2; // add numbers
 Assignment
 Calculates
statement
sum of number1 and number2 (right hand
side)
 Uses assignment operator = to assign result to variable sum
 Read as: sum gets the value of number1 + number2
 number1 and number2 are operands
Displaying result
12
System.out.printf( "Sum is %d\n: " , sum ); // display sum
25
 Use
System.out.printf to display results
 Format specifier %d
 Placeholder
for an int value
System.out.printf( "Sum is %d\n: " , ( number1 + number2 ) );
 Calculations
can also be performed inside printf
 Parentheses around the expression number1 +
number2 are not required
Variables stored in memory
13


Variable has a name, a type, a size and a value
Variables are stored in main memory
 Size
of memory depends on the type
 Name corresponds to location in memory
 Mapping


performed by compiler
Assignment statement: place new value into
variable, replaces (and destroys) previous value
Reading variables from memory does not change
them
Arithmetic Expression
14

Arithmetic calculations
for multiplication
 / for division
 % for remainder
 +, *

Integer division truncates remainder
 12

/ 5 evaluates to 2
Remainder operator % returns the remainder
7 % 5 evaluates to 2
Arithmetic operators
15
Java
operation
Arithmetic Algebraic
operator
expression
Java
expression
Addition
+
f+7
f + 7
Subtraction
–
p–c
p - c
Bm
b * m
Multiplication *
Division
/
x / y or
or x ÷ y
x / y
Exercise: write an expression to convert temperature from
Farenheith degree to Celsus degree:
Hint: Tf = (9/5)*Tc+32;
Tc = temperature in degrees Celsius
Tf = temperature in degrees Fahrenheit
Operator Precedence
16

Some arithmetic operators act before others (i.e.,
multiplication before addition)
 Use
parenthesis when needed
Operator(s) Operation(s) Order of evaluation
(precedence)
*
Multiplication
/
Division
%
Remainder
+
Addition
-
Subtraction
Evaluated first. If there are
several operators of this type,
they are evaluated from left to
right.
Evaluated next. If there are
several operators of this type,
they are evaluated from left to
right.
Casting
17




To calculate average value of count # of integers:
average = (double) total / count;
Unary cast operator (double) creates a temporary floatingpoint copy of its operand.
 The value stored in its operand is unchanged.
 To perform a floating-point calculation, temporarily treat
these values as floating-point numbers for use in the
calculation.
Cast operator performs explicit conversion (or type cast).
Operands’ type in an arithmetic expressions should be identical.
 In an expression containing values of types int and double, int
values are promoted to double values for use in the
expression.
 count is casted to double too, this is called Promotion (or
implicit conversion).
Cast operators
18

Cast operators are available for any type.


Sometimes this lead to loss of information
int dollarAmount;
double changes = amountReceived – amountDue;
dollarAmount = (int) changes;
Cast operators associate from right to left



same precedence as other unary operators, such as unary + and
unary –
double a=10.35;
double b=(double)(int)a;
Good Programming Practice
19



Refer to operator precedence chart when writing
expressions containing many operators.
When uncertain, use parentheses to force the
order
Some operators, such as assignment, =, associate
from right to left rather than from left to right.
Exercise
20

Exercise: write an expression to convert temperature
from Farenheith degree to Celsus degree:
 Tf



= (9/5)*Tc+32;
Tc : temperature in degrees Celsius
Tf : temperature in degrees Fahrenheit
In lab1 assignment, you will implement a Cashier
program. One task is to direct the cashier to give
changes to the customer:
 If
the change is $12.34, the program displays
 “Give
12 dollars, 1 quarter, 5 nickels and 4 pennies.”
Problem Solving Approach
21

Don’t start coding right away
 Unless

it’s a trivia problem
Before writing a program to solve a problem
 Have
a thorough understanding of the problem
 Carefully plan your program to solving the problem,
i.e., algorithm


Understand available building blocks
Employ proven program-construction techniques
 Top-down
technique
Algorithms
22



An algorithm is a procedure for solving a problem in terms of
 the actions to execute and
 the order in which these actions execute
One Rise-and-shine algorithm:
(1) Get out of bed;
(2) take off pajamas;
(3) take a shower;
(4) get dressed;
(5) eat breakfast;
(6) carpool to work.
Easier?

Now how to take a shower …
Pseudocode
23

Pseudocode: an informal language for describing
algorithms without having to worry about language
details



Helps you “think out” a program before attempting to code
Carefully prepared pseudocode can easily be
converted to a corresponding program.
Like program language, also have control structure for
constructing loops, selection
Control Structures
24



Sequential execution: Statements in a program
execute one after the other in the order in which they
are written.
Transfer of control: Statements in a program that
which enable change of next statement to execute,
i.e., not necessarily next one in sequence.
All programs can be written in terms of only three
control structures—the sequence structure, the
selection structure and the repetition structure.
Selection statements
25

if statement: Single-selection statement
Performs an action, if a condition is true; skips it, if false.
 Selects or ignores a single action (or group of actions).


if…else statement: Double-selection statement
Performs an action if a condition is true and performs a
different action if the condition is false.
 Selects between two different actions (or groups of actions).


switch statement: Multiple-selection statement
Performs one of several actions, based on the value of an
expression.
 Selects among many different actions (or groups of actions).

Repetition/Looping Statements
26


Perform statements repeatedly while a loopcontinuation condition remains true.
while and for statements perform the action(s) in their
bodies zero or more times



if the loop-continuation condition is initially false, the body
will not execute.
The do…while statement performs the action(s) in its
body one or more times.
if, else, switch, while, do and for are keywords.
Condition
27
Selection and repetition statements involve conditions :
If the condition is true, then the body of
if (condition)
the if statement executed
body
while (condition)
while the condition is true, repeat to execute
the body of the loop
body


Condition: expression that is either true or false

can be formed using equality or relational operators
if ( number1 >= number2 )
System.out.printf( "%d >= %d\n", number1, number2 );
Equality and relational operators
28
Standard algebraic Java equality Sample
equality or relational or relational Java
operator
operator
condition
Equality operators


Relational operators



≤
Meaning of
Java condition
==
!=
x == y
x != y
x is equal to y
x is not equal to y
>
<
>=
<=
x
x
x
x
x is greater than y
x is less than y
x is greater than or equal to y
x is less than or equal to y
> y
< y
>= y
<= y
• No spaces between symbols in operators ==, !=, >= and <=.
• Reversing operators !=, >= and <=, as in =!, => and =<, is a syntax error.
Common Programming Error
29

Confusing equality operator, ==, with assignment
operator, =, leads to logic error or syntax error.
== read as “is equal to”
 = read as “gets”, or “gets the value of.”

if Single-Selection Statement
30

Pseudocode
If student’s grade is greater than or equal to 60
Print “Passed”


If the condition is false, the Print statement is ignored,
and the next pseudocode statement in order is
performed.
Indent the body of the statement


Emphasizes the inherent structure of structured programs
The preceding pseudocode in Java:
if ( studentGrade >= 60 )
System.out.println( "Passed" );
if…else Double-Selection Statement
31


if…else double-selection statement: specify an action to
perform when the condition is true and a different action
when the condition is false.
Pseudocode
if student’s grade is greater than or equal to 60
Print “Passed”
else
Print “Failed”

Converting the pseudocode statement into Java:
if ( grade >= 60 )
System.out.println( "Passed" );
else
System.out.println( "Failed" );

Note that the body of the else is also indented.
Conditional Operator
32

Conditional operator (?:)—shorthand for if…else.
System.out.println(
studentGrade >= 60 ? "Passed" : "Failed" );

Ternary operator (takes three operands)
studentGrade >= 60 ? "Passed" : "Failed“
a boolean expression
evaluates to a boolean
value (true or false)

the value if the boolean
expression is true
the value if the boolean
expression evaluates to false.
Evaluates to the string "Passed" if the boolean expression
studentGrade >= 60 is true and to the string "Failed" if it is
false.
Nested If…else statement
33

Nested if…else statements : place an if…else statement as the
body for another if … else statement


Useful for testing multiple cases
Pseudocode:
If student’s grade is greater than or equal to 90
Print “A”
else
If student’s grade is greater than or equal to 80
Print “B”
else
If student’s grade is greater than or equal to 70
Print “C”
else
If student’s grade is greater than or equal to 60
Print “D”
else
Print “F”
Nested if…else Statement
34

In Java:
if ( studentGrade >= 90 )
System.out.println( "A" );
else
if ( studentGrade >= 80 )
System.out.println( "B" );
else
if ( studentGrade >= 70 )
System.out.println( "C" );
else
if ( studentGrade >= 60 )
System.out.println( "D" );
else
System.out.println( "F" );
Nested if … else statement
35


Alternative formatting
if ( studentGrade >= 90 )
System.out.println( "A" );
else if ( studentGrade >= 80 )
System.out.println( "B" );
else if ( studentGrade >= 70 )
System.out.println( "C" );
else if ( studentGrade >= 60 )
System.out.println( "D" );
else
System.out.println( "F" );
The two formats are identical except for the spacing and
indentation, which the compiler ignores.
if…else Double-Selection Statement
36

Dangling-else problem: Which if does the else associated with ?
if ( x > 5 )
if ( y > 5 )
System.out.println( "x and y are > 5" );
else
System.out.println( "x is <= 5" );

Java always associates an else with the immediately preceding if,
unless told to do otherwise by braces ({ and }).

The compiler actually interprets the statement as
if ( x > 5 )
if ( y > 5 )
System.out.println( "x and y are > 5" );
else
System.out.println( "x is <= 5" );
This is a logic error, as the program is not doing what the programmer
intend it to do.
if…else Double-Selection Statement
37

To force the nested if…else statement to execute as it
was originally intended:
if ( x > 5 )
{
if ( y > 5 )
System.out.println( "x and y are > 5" );
}
else
System.out.println( "x is <= 5" );

Braces indicate that the second if is in the body of the
first and that the else is associated with the first if.
Block Statement
38

To include several statements in the body of an
if, or the body of an else, enclose the statements
in braces.
 Statements
contained in a pair of braces form a
block.
 A block can be placed anywhere that a single
statement can be placed.
if ( grade >= 60 )
System.out.println("Passed");
else
{
System.out.println("Failed");
System.out.println("You must take this course again.");
}
Empty Statement
39

Note that there is no ; after the condition
if (x>0);
System.out.println (″x is not greater than 0″);

Above code has no syntax error
 Compiler
interpret ; as empty statement
If (x>0);
System.out.println ((″x is not greater than 0″);
 Recall
a block statement can be placed anywhere a
single statement can be placed, so does an empty
statement.

Another example of logic error !
Exercise
40



Review logic operators: &&, ||, ! , i.e., and, or,
not operators.
Write a piece of code that test whether a given
year is prime year or not
Write a piece of code that test whether a given
date (specified by year, month and day) is a valid
date or not
while Repetition Statement
41


Repetition statement—repeats an action while a
condition remains true.
Pseudocode
While there are more items on my shopping list
Purchase next item and cross it off my list


Repetition statement’s body may be a single
statement or a block.
Eventually, the condition will become false. At this
point, the repetition terminates, and the first
statement after the repetition statement executes.
while Repetition Statement (Cont.)
42

Example: find smallest power of 3 that is larger than 100.
int product = 3;
while ( product <= 100 )
product = 3 * product;
System.out.printf (“smallest power of 3 greater than 100 is %d\n”,
product);




Each iteration multiplies product by 3, so product takes on the
values 9, 27, 81 and 243 successively.
When variable product becomes 243, the while-statement
condition—product <= 100—becomes false.
Repetition terminates. The final value of product is 243.
Program execution continues with the next statement after the
while statement.
Formulating Algorithms: Counter-Controlled
Repetition
43

A class of ten students took a quiz. The grades (integers in the
range 0 to 100) for this quiz are available to you. Determine the
class average on the quiz.



The algorithm: input each grade, keep track of the total of all
grades input, perform the averaging calculation and print the
result.
Use counter-controlled repetition to input the grades one at a
time.


The class average is equal to the sum of the grades divided by the
number of students.
A variable called a counter (or control variable) controls the number
of times a set of statements will execute.
Counter-controlled repetition is often called definite repetition,
because the number of repetitions is known before the loop
begins executing.

44
total: a variable used to accumulate the sum of several values.

A counter is a variable used to count.

Variables used to store totals are normally initialized to zero before being
used in a program.
45
46
Review: How to convert the while loop into for loop ?
47
Formulating Algorithms: Sentinel-Controlled
Repetition
48

Develop a class-averaging program that processes
grades for an arbitrary number of students





E.g., “Use -1 to end”
Use a special value, sentinel value, to indicate “end of
data entry.”
A sentinel value must be an unacceptable input value.
Indefinite repetition: the number of repetitions is not
known beforehand.
Exercise: write a pesudocode for above problem
49
50
Reminder the user about
the sentinel
51
We use while loop here… Can we rewrite the code use do loop ?
Which loop is better ?
52
Some shorthand Operators
53


Increment operator, ++, decrement operator, -Compound assignment operators: +=, -=, *=, …
Summary
54


We review basic constructs in Java in this class
Read from standard input, write to standard output
 Focus
now on a text-based program run from terminal
 GUI programming will be introduced later

Variables, primitive data type, arithmetic expression
 Assignment
operator, arithmetic operators
 Cast: converting a variable to another data type

Control structures: sequence, selection and repetition
Summary (cont’d)
55

Condition: an expression that has a boolean value
 Used
in selection, loop
 Construct a condition: relational/comparison operators,
boolean operators (&&, ||, !)

Selection statement:
 If

…statement, if … else statement
Repetition statement
 while,
do, for loop
 Should know how to convert between them …
Summary (cont’d)
56


Algorithm, Pseudocode
Construct of a loop for solving problems
 Initialization
 Body
 Condition

Whenever writing a loop, be sure to verify that it
works
 Are
variables initialized before the loop?
 Will the loop terminate properly?