View
216
Download
2
Embed Size (px)
Citation preview
About Programs Data and method (procedures, routines, functions) are two
fundamental elements of programming
Two basic tasks in constructing a program Define data types and data elements Define procedures that process data
Two schemes of building a program Procedure oriented (what we have been learning) Object oriented (to be covered soon)
Data Types Java is a strong typed language: every data element (literal or
variable) has a “fixed” type
We have learned built-in types in Java, e.g., int, double, String (We will learn how to define our data types later)
Before using a variable, you must make sure that its type has been clearly “declared”
It is important to choose suitable data types in information processing.
Built in Data Types Numerical types are used for math computing
Numeric Types: byte, short, int, long, float, double “int” literals: 10, -5 “long” literals: 1034678L “double” literals: 1.234, -2.5, 1.0e10 “float” literals: 1.234f
Numerical Operators Operators:
Binary operators: +, - , * , / , % Unary operators: ++, -- (only for variables), +, -
Built in Data Types Boolean types are for logic computing
Boolean Types: boolean liberals: true, false
Operators: &&(and), ||(or), ! (not)
Comparison Boolean type can be generated by comparison operations:
>, <, >=, <=, ==, !=
For example, expression (a +c >= b) has a boolean type
Built in Data Types Character and string types are for text processing
Character Type: char literals: ‘a’, 3’, ‘+’, ‘/n’, ‘/t’, ‘#’
String Type: String literal: “Hello World”, “1234”, “1+2” Operator: +
“123” + ”abc”=“123abc” “123” + 4 = “1234” “123” + ‘4’ = “1234” Pay attention to the difference of
1 + 2 + “123” “123” + 1 + 2
The Precedence of Operators
( )!, unary -, unary +, ++(post), --(post)++(pre), --(pre)*, /, %+, -<, <=, >, >===, !=&&||=
High
low
Example: a++ > 5 || b < 6((a++) > 5) || (b < 6)
a && b || c && d <=> (a &&b) || (c && d)
Type in Java Every entity in Java that has a “value” has association with
specific data types.
Literals: 1.5, 2000, 1.0e20 Variables: n, m, counter, isPostive Expressions: counter++, n+m Functions: input and output must have clearly declared
variables with certain types.
Variables Variables are data elements whose values can “change” Variables are referenced by names Each variable must be declared to be of some “type” Assignment operation “=“
int n; double x, y;n = 10 + 5 - 4;int m = 20;n = m + n;x = 100 / n;n = x; illegal operation
n = (int) x;
promotion
variable = expression;
+=-=*=/=
Special Assignments
How can you changethe value of a variable?
The Scope of Variables Variable Scope: the part of code where you can reference a
variable.
{ int y; int x; { int z; }
}
Scopeof yScope
of x
{ int x; int y;
}
Differentx, y fromthe previous block
Scopeof z
A block in Java isusually enclosed by { }for instance: A function body,or blocks in if, for or while statements.
Procedures Java defines different language constructs for writing
procedures – an action or sequential of actions on data elements. The flow control statements
Straight-line code “If statement” for conditional branches “Loops” such as “while” loops or “for” loops for iterative
procedures.
Function (routine) Function is a basic tool in Java for “information hiding” The key of a function is the “interface”:
the input and output of the function.
Straight Line Code
Logic group1
Logic group 2
Logic group 3
Good program structure
Logic group 3
Logic group 2
Logic group1
Bad program structure
If Statements
Nested if statement:
if (isA) doA;if (isB) doB;if (isC) doC;
if (isA) doA; else if (isB) doB; else if (isC) doC;
If (condition) { statements}else { statements}
or
If (condition) { statements}
Loops
while statement:while (condition) { statements}
for statement:for(initialization; condition; update) { statements}
• while loop is a general one. If you do not know the number ofIterations, you should use a while loop.
• For loop is more compact when dealing with counting up ordown a control variable.
• Prefer “for” loop when possible.
• Do not use “for” loop is “while” loop is more appropriate.
While Loops
double s = 0;int n = 0;while ( !StdIn.isEmpty() ) { double x = StdIn.readDoulbe(); s += x; n ++;}s = s / n;
while(s.charAt(0) ==‘ ‘) s = s.substring(1);
While (n%2 == 0) { n = n/2;}
Average:
Removewhite space:
Removefactor 2:
For Loops int N = 100; int s = 0; for (int i = 0; i < N; i++) { s += i; } double p = 0; for (int k = N ; k >= 1; k --) { p = p + (1.0/K) ; }
for (int i = 0; i < N; i++) { StdOut.println(); for (int j = 0; j < N; j ++) { if ( i % 2 == 0 && j % 2 == 0) StdOut.print(“*”); else if (I % 2 == 1 && j % 2 ==1) StdOut.print(“*”); else StdOut.print(“ “); }}
Sum:
Harmonic number:
Checkerboard:
More about Loops We can solve many problems using iterative methods.
But, how do I know a loop is correct?
There are quite a lot of things going on in a loop. Interestingly, the most important feature you should pay attention to is not something that changes but something that does not change.
Loop Invariant
int N = 100; int s = 0; for (int i = 0; i < N; i++) { s += i; }
loop invariant: After each iteration, s equals the summation from 0 to i.
int v = 1; while (v < N/2) v = 2*v;
loop invariants: At the beginning of each loop, v < N/2 After each loop v < N v is a power of 2 (true for both the beginning and the end of a loop)
1. The loop will terminate somehow2. Some loop invariant holds in each each loop.3. When the loop terminates, we obtain the desired result .
Checking a Loop
public static boolean isPowerOf2(int n) { while (n % 2 == 0) { n = n / 2; } if (n == 1) { return true; } else { return false; }}
Input and Output Standard Input and Standard output
Read from standard input, e.g., StdIn.readInt() Write to standard output, e.g., StdOut.print(x) Redirection: we can read from a file by using standard input and output.
Data Processing “Boston” 2 “San Diego” 40
… --------------------------------------------------------- int lowestTemperature = 200; String coldestCity = “”; while (!isEmpty()) { String city = StdIn.getString(); int temperature = StdIn.getInt(); if (temperature < lowestTemperature) { lowestTemperature = temperature; coldestCity = city; } }
Function Information Hiding
Using functions, we can hide the details of a procedure. This is the basic way of constructing large systems.
The most important feature of a function is its “interface” public static TYPE functionName(TYPE a1, TYPE a2, …) output input
Design by contract Each function is a “contract”.
From the client side (the caller): the function requires that the client must fulfill some condition before calling some procedure. For instance, function Math.sqrt(x) requires that x >= 0.
The function is a service provider: it must complete some specified task. For instance, Math.sqrt(x) will compute the square root of x when the function returns.
The client condition is termed as “precondition” and the service condition is called “postcondition”.
Math Functions Math functions
double x = -1000.0;double y = Math.abs(x);
Others: Math.sin() Math.cos() Math.random() Math.round() Math.max()…
String Functions The following functions can be used to process strings
String s = “abcd”;Char c = s.charAt(2);Int l = s.length();String t = s.substring(0,2);t = s.substring(2);
c = ‘c’l = 4
t = “ab”t = “cd”
abcdefg1234567
position0
Position13
Recursion Recursion is an important method to construct functions to
solve problems.
To construct a recursive function: You should have a method to “reduce” your problem into smaller
same problems that can be combined to solve the current problem.
You know how to solve the trivial base problem. You make sure that the reeducation plan will NOT go infinitely.
Recursion Example:
Example: A function that returns a string that reverse the original one, e.g. if the input is “abc” the output is “cba”.
Base case: If the input is has a single character, return itself.Reduction plan: Reverse the substring starting from the second character and then connected with the first character.
String reverseString(String str){ if (str.length() == 1) return str; string s = reverseString(str.substring(1)) + str.charAt(0); return s;}
Recursion Example: Example: Test whether a number is a power of 2.
boolean isPowerOfTwo(int n){ if (n == 1) return true; if (n % 2 == 1) return false; return isPowerOfTwo(n/2); }
Iteration or Recursion? Even though iteration is more appealing at first thought,
recursion solution is usually easier to construct (bug free).
Some times recursion is not efficient (to compute a Fibonacci sequence).
The Procedure based Programming
Get initial time
Draw the Panel
Start the Clock
int hour = Integer.parseInt(args[0]);int minute = Integer.parseInt(args[1]);int second = Integer.parseInt(args[2]);
drawFace()
while (true) { clearHandsDrawingRegion(); drawHands(hour, minute, second); hour = updateHour(hour, minute, second); minute = updateMinute(hour, minute, second); second = updateSecond(hour, minute, second); wait(1);}
Function blocks Procedures in Java
The clock:
public static void main(String[] args) { int hour = Integer.parseInt(args[0]); Int minute = Integer.parseInt(args[1]); int second = Integer.parseInt(args[2]); drawFace(); while (true) { clearHandsDrawingRegion(); drawHands(hour, minute, second); hour = updateHour(hour, minute, second); minute = updateMinute(hour, minute, second); second = updateSecond(hour, minute, second); wait(1); }
public class Clock { public static void drawMarkers() { … } public static void drawLetters() { … } public static void drawFace() { drawMarkers(); drawLetters(); } public static void clearHandsDrawingRegion() { … } public static void drawHands(int h, int m, int s) { … } public static int updateHour(int h, int m, int s) { … } public static int updateMinute(int h, int m, int s) { … } public static int updateSecond(int h, int m, int s) { … }
The structureof the wholeprogram