main and control flow programming without objecteditor main class control flow “real”...

70
Main and Control Flow • Programming without ObjectEditor • Main Class • Control Flow •“Real” Programming •Linear •Branching •Looping • Programmer-Defined Overloading • Console Input

Post on 20-Dec-2015

257 views

Category:

Documents


0 download

TRANSCRIPT

Main and Control Flow

• Programming without ObjectEditor

• Main Class

• Control Flow

•“Real” Programming

•Linear

•Branching

•Looping

• Programmer-Defined Overloading

• Console Input

• Programmer-Defined Library Class

Programming Vs Bicycle Riding

Statements Expressions

Primitive Types

Least Privilege Interfaces Reuse Stepwise-

Refinement

Interface

Implements

Class

Method

Return Type/ Formal Parameter

Statement

Starting with the Big Picture

Variable (State)

Local Variable

Method Header

Signature

Name

Named Constant

Statement List

Statement ...

Statement

Starting with the Small Picture

Class

Method

Return Type/ Formal Parameter

Statement List

Statement ...

Variable (State)

Local Variable

Interface

Method Header

Signature

Name

Named Constant

Implements

Statement

Interface

Implements

Class

Method

Return Type/ Formal Parameter

Statement

Starting with the Abstractions

Variable (State)

Local Variable

Method Header

Signature

Name

Named Constant

Statement List

Statement ...

Statement

Data Abstraction

exports

Operation Abstraction

exports

Interface

Implements

Class

Method

Return Type/ Formal Parameter

Statement

Starting with Optional Components

Variable (State)

Local Variable

Method Header

Signature

Name

Named Constant

Statement List

Statement ...

Statement

Real-Work

Required

Focussing on Control Flow (“Real Programming”)

StatementStatement List

Statement ...

Statement List

Statement ...

Statement

Linear

Statement List

Stmt

Statement

Stmt

BranchingStatement List

Stmt

Statement

Stmt

Looping

Removing Training WheelsText Editor

ALoanPair Source Code

creates

Java Compiler

reads

ALoanPairObject (Byte) Code

creates

Java Interpreter

ALoanPair Instance

getTotalLoan()

instantiates

calls

ObjectEditor

main

calls

, Main Class

Main ClassObject (Byte) Code

Static method

Equivalent User Interfaces

Algorithm (edit)

Algorithm (edited)

Algorithm (soln)

• Create ALoanPair instance based on the two values entered by the user in the console window.

• Print the properties of the loan pair object in the console window.

• Pause until user presses some keystroke.

public static void main (String[] args) {

LoanPair loanPair = new ALoanPair(readCarLoan(), readHouseLoan());

print (loanPair);

pause();

}

Main Method

Method chaining

List of user-supplied argumentsmain header

public static void main (String[] args) {

Loan carLoan = readCarLoan();

Loan houseLoan = readHouseLoan();

LoanPair loanPair = new ALoanPair(carLoan, houseLoan());

print (loanPair);

pause();

}

Main Method without Method Chaining

Undefined

Stepwise refinement

readCarLoan()

readCarLoan()

• Prompt user

• Return an instance of ALoan constructed from the principal.

public static Loan readCarLoan() {System.out.println("Please enter car principal:");return new ALoan(readInt());

}

Called by class method (main)

Undefined

static DataInputStream dataIn = new DataInputStream (System.in); public static int readInt() {

try {return Integer.parseInt(dataIn.readLine());

} catch (Exception e) {System.out.println(e);return 0;

}}

readInt()• Wait for the user to enter a string (of digits) on the next line.

• Return the int represented by the string.

• In case the user makes an error or terminates input before entring a valid int, return 0 and print an error message.

try {return Integer.parseInt(dataIn.readLine());

} catch (Exception e) {

System.out.println(e);return 0;

}

Try-Catch Block

Exception Object

Program fragment that can cause exception

Exception Handler

public class ALoanPairDriver {

...

}

import java.io.DataInputStream;

public class ALoanPairDriver {

….

…...

}

Importing a Package

new DataInputStream(System.in)

new java.io.DataInputStream(System.in)

package java.io;

public class DataInputStream {

….

}

short name

full name

Import Declaration

Printing a LoanPair

Printing a LoanPair

public static void print (LoanPair loanPair) {System.out.println("****Car Loan*****");print(loanPair.getCarLoan());System.out.println("****House Loan****");print(loanPair.getHouseLoan());System.out.println("****Total Loan****");print (loanPair.getTotalLoan());

}

public static void print (Loan loan) { System.out.println("Principal:" + loan.getPrincipal()); System.out.println("Yearly Interest:" + loan.getYearlyInterest()); System.out.println("Monthly Interest:" + loan.getMonthlyInterest());}

Programmer-defined Overloading

public static void pause() {try {

System.in.read();} catch (Exception e) {

System.out.println(e);}

}

pause()Returns single char

System.out.println(pause());

Legal Expression & Statement

public static void pause() {try {

System.in.read();} catch (Exception e) {

System.out.println(e);}

}

Expression Vs Statement

System.out.println(pause());

5 + 3;

Illegal

Function Calls

• Can be used as expression

• Can be used as statement– When return value is to be ignored– Rarely happens– Check program to see all return values being

used as expressions

• Other expressions not statements

• Procedure calls never expressions

Multi-level Algorithm/Code

main

print (Loan)

readCarLoan readHouseLoan print(LoanPair) pause

readInt

Class-Level Decomposition

Monolithic Main Class(Loan User Interface and Loan Computation)

Object EditorProgrammer-defined Class(A Loan Pair)

Driver(ALoanPairDriver)

Class-Level Decomposition

main

print (Loan)

readCarLoan readHouseLoan print(LoanPair) pause

readInt

Separate Class

pause()readInt()

readDouble()

readBoolean()

readChar()

Keyboard

readString()

Using Keyboard

public static Loan readCarLoan() {System.out.println("Please enter car principal:");return new ALoan(readInt());

}return new ALoan(Keyboard.readInt());

Separation of Concerns

• Make independent piece of code as separate method.

• Make independent set of methods as separate class.

• Use operation and data abstraction!

Running Main

Single-Stepping

Step Into Vs Step Over

Inspecting Variables

Conditionals

printPassFailStatus(95)

printPassFailStatus(25)

public static void printPassFailStatus(int score) {if (score < PASS_CUTOFF)

System.out.println("FAILED");else

System.out.println("PASSED");}

PASS

FAIL

If-else Statement

if (<bool expr>)<statement 1>

else<statement 2>

If-Else Statement

<bool expr>true false

<statement 1> <statement 2>

Compound Statementpublic void fancyPrintGrade(int score) {

if (score < PASS_CUTOFF) {

System.out.println("**************");System.out.println("FAILED");System.out.println("**************");

}else {

System.out.println("**************");System.out.println("PASSED");System.out.println("Congratulations!");System.out.println("**************");

} }

Avoding Code Duplication in If-Else

public void fancyPrintGrade(int score) { System.out.println("**************");

if (score < PASS_CUTOFF) System.out.println("FAILED");

else {System.out.println("PASSED");System.out.println("Congratulations!");

}System.out.println("**************");

}

Avoding Code Duplication in If-Else

public void fancyPrintGrade(int score) { System.out.println("**************");

if (score < PASS_CUTOFF) System.out.println("FAILED");

else {System.out.println("PASSED");System.out.println("Congratulations!");

}System.out.println("**************");

}

If Statement

if (score == MAX_SCORE) System.out.println ("Perfect Score! Congratulations!");

if (<bool expr>) <statement>;

if Statement

<bool expr>true

false<statement>

Nested if-elsepublic static char toLetterGrade (int score) {

if (score >= A_CUTOFF) return 'A';else if (score >= B_CUTOFF) return 'B';else if (score >= C_CUTOFF) return 'C';else if (score >= D_CUTOFF) return 'D';else return 'F';

}

Nested If-Elseif (score >= A_CUTOFF) return 'A';else

if (score >= B_CUTOFF) return 'B';else

if (score >= C_CUTOFF) return 'C';

else if (score >= D_CUTOFF) return 'D'; else

return 'F'; 

Nested If-Else

Looping

printHello(2)

hello

hello

printHello(3)

hello

hello

hello

Loops

int counter = 0;if (counter < n) { counter = counter + 1; System.out.println (“hello”);}

public static void printHello(int n) {

}

Loops

int counter = 0;while (counter < n) { counter = counter + 1; System.out.println (“hello”);}

public static void printHello(int n) {

}

If Vs While Statement

if (<bool expr>) <statement>;

while (<bool expr>) <statement>;

if Statement

<bool expr>true

false<statement>

while Statement

<bool expr>true

false<statement>

while loop

<bool expr>

true

false

<statement >

Sentinel-based Folding

Adding Fixed Number of Loans

Loan loan1 = readLoan();Loan loan2 = readLoan();Loan loan3 = readLoan();Loan loan4 = readLoan();Loan sumLoan = ALoan.add(loan1, ALoan.add(loan2,

ALoan.add(loan3, loan4)));print (sumLoan);

Generalizing to Variable # Loans

Loan loan1 = readLoan();Loan loan2 = readLoan();Loan loan3 = readLoan();Loan loan4 = readLoan();…Loan loanN = readLoan();Loan sumLoan = ALoan.add(loan1, ALoan.add(loan2,

ALoan.add(loan3, Aloan.add(loan4, ……(add (loanN-1, loanN)*;print (sumLoan);

Loops + Arrays

Recursion

Variable # of Statements

Variable # of Subexpressions (function calls)

Space Efficient Adding of Fixed Number of Loans

Loan loan1 = readLoan();Loan loan2 = readLoan();Loan sumLoan = ALoan.add(loan1, loan2);loan1 = readLoan(); // 3rd loansumLoan = ALoan.add(sumLoan, loan1);loan1 = readLoan(); // 4th loansumLoan = ALoan.add(sumLoan, loan1);print (sumLoan);

More Space Efficient Adding of Fixed Number of Loans

Loan sumLoan = readLoan(); //first loanLoan nextLoan = readLoan(); //second loansumLoan = Aloan.add(nextLoan, sumLoan);nextLoan = readLoan(); // 3rd loansumLoan = ALoan.add(sumLoan, nextLoan);nextLoan = readLoan(); // 4th loansumLoan = ALoan.add(sumLoan, nextLoan);print (sumLoan);

More Space Efficient Adding of Variable Number of Loans

Loan sumLoan = readLoan(); //first loanLoan nextLoan = readLoan(); //second loansumLoan = Aloan.add(nextLoan, sumLoan);nextLoan = readLoan(); // 3rd loansumLoan = ALoan.add(sumLoan, nextLoan);nextLoan = readLoan(); // 4th loan

sumLoan = ALoan.add(sumLoan, nextLoan); nextLoan = readLoan(); //Nth loan sumLoan = ALoan.add(sumLoan, nextLoan); nextLoan = readLoan(); //sentinel

print (sumLoan);

N-1 repetitions

While Loop

Loan sumLoan = readLoan(); //first loan Loan nextLoan = readLoan(); //second loan while (nextLoan().getPrincipal() >= 0) {

sumLoan = ALoan.add(nextLoan, sumLoan);nextLoan = readLoan(); // next loan or sentinel

} print (sumLoan);

-1

Input Result

Program waits for ever for second loan

Boundary Condition

Loan sumLoan = new ALoan(0); //initial value Loan nextLoan = readLoan(); //second loan while (nextLoan().getPrincipal() >= 0) {

sumLoan = ALoan.add(nextLoan, sumLoan);nextLoan = readLoan(); // next loan or sentinel

} print (sumLoan);

Correct Solution

ALoan.add(new ALoan(0), add(loan1, add (…., loanN)

identity

Loan sumLoan = new ALoan(0); //initial value Loan nextLoan = readLoan(); //second loan while (nextLoan().getPrincipal() >= 0) {

sumLoan = ALoan.add(nextLoan, sumLoan);nextLoan = readLoan(); // next loan or sentinel

} print (sumLoan);

A Single Sentinel Value

Loan sumLoan = new ALoan(0); //initial value Loan nextLoan = readLoan(); //second loan while (nextLoan().getPrincipal() >= 0) {

sumLoan = Aloan.add(nextLoan, sumLoan);nextLoan = readLoan(); // next loan or sentinel

} print (sumLoan);

A Single Loan

Loan sumLoan = new ALoan(0); //initial value Loan nextLoan = readLoan(); //second loan while (nextLoan().getPrincipal() >= 0) {

sumLoan = Aloan.add(nextLoan, sumLoan);nextLoan = readLoan(); // next loan or sentinel

} print (sumLoan);

Two Loans

Multiplying Numbers (edit)

???

Multiplying Numbers (edited)

???

Multiplying Numbers int product = 1; int num = Keyboard.readInt(); while (num >= 0) { product = product*num; num = Keyboard.readInt(); }

print (product);

1*20*2*3

Identity

Comparing Two Solutions int product = 1; int num = Keyboard.readInt(); while (num >= 0) { product = product*num; num = Keyboard.readInt(); }

print (product);

Loan sumLoan = new ALoan(0); Loan nextLoan = readLoan(); while (nextLoan().getPrincipal() >= 0) {

sumLoan = ALoan.add(nextLoan, sumLoan); nextLoan = readLoan();

} print (sumLoan); // print value

Identityresult

nextVal

read first value

read other values

Binary folding function

!isSentinel(nextVal)

Generalized Folding of a Sentinal-Terminated List

a1

f

f

f

ana3a2

f: T, T T

F(x, I) x

T result = I;T nextValue = getNextValue()while (!isSentinel(nextValue)) { result = f(result, nextValue); nextValue = getNextValue(..);}

Generalized Folding SolutionLoan, int new ALoan(0), 1

ALoan.add(), *

>= 0

Comparing Two Solutions (Comments)

int product = 1; //identity int num = Keyboard.readInt(); // read next list value while (num >= 0) { // sentinel checking product = product*num; // binary folding function num = Keyboard.readInt(); // read next value }

print (product);// print value

Loan sumLoan = new ALoan(0); //identity Loan nextLoan = readLoan(); // read next list value while (nextLoan().getPrincipal() >= 0) {// sentinel checking

sumLoan = Aloan.add(nextLoan, sumLoan); // binary folding functionnextLoan = readLoan(); // read next list value

} print (sumLoan); // print value