Main and Control Flow Programming without ObjectEditor Main Class Control Flow “Real” Programming Linear Branching Looping Programmer-Defined Overloading.

Slides:



Advertisements
Similar presentations
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Advertisements

INSTRUCTOR: SHIH-SHINH HUANG Windows Programming Using Java Chapter4: Control Statements Part I.
Java Programming, 3e Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
C OMP 110 M AIN & C ONSOLE I NPUT Instructor: Jason Carter.
Java review and more. Class Header  Public class Welcome  Case sensitive  Body of the class must be enclosed by braces.
Comp 114 Foundations of Programming Instructor: Prasun Dewan.
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
Class Variables & Methods More on dependencies Representation and representation errors Primitive vs. Object Properties Class Variables/Methods Primitive.
Exceptions Problems with error reporting so far –Either ignored exceptions or terminated program on first error. –Error handling and regular code mixed.
Loops More loops Off-by-one errors Infinite loops Nested Loops.
Datalogi A 1: 8/9. Book: Cay Horstmann: Big Java or Java Consepts.
Programmer-Defined Types Object Types as Programmer-defined Types Two-way Dependencies Representation Errors Primitive Vs Object Properties Constructors.
More on Conditionals Miscellaneous (Side effects) Style issues Early returns.
Object Types Primitive types Primitive Vs Object Types Types Classes ABMISpreadsheet AnotherBMISpreadsheet Interfaces BMISpreadsheet Loan Stringdoubleint.
Exceptions Problems with error reporting so far –Either ignored exceptions or terminated program on first error. –Error handling and regular code mixed.
Class Variables & Methods More on dependencies Representation and representation errors Primitive vs. Object Properties Class Variables/Methods Primitive.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
Chapter 7: User-Defined Methods
Midterm Exam 2 75 points 1 min per point Allocate time proportionate to points Closed book Chapters 6-9 Look at exercises.
Comp 114 Foundations of Programming Instructor: Prasun Dewan (Pr  sün Divän)
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
C OMP 110 M AIN & C ONSOLE I NPUT Instructor: Sasa Junuzovic.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Java Programming: From the Ground Up
The Java Programming Language
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Slide: 1 Copyright © AdaCore Subprograms Presented by Quentin Ochem university.adacore.com.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Java Programming, 2E Introductory Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
C OMP 110 L OOPS Instructor: Prasun Dewan 2 P REREQUISITE Conditionals.
Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
By Mr. Muhammad Pervez Akhtar
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Aside: Running Supplied *.java Programs Just double clicking on a *.java file may not be too useful! 1.In Eclipse, create a project for this program or.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
CPSC 233 Tutorial January 21 st /22 nd, Linux Commands.
CompSci 230 S Programming Techniques
Information and Computer Sciences University of Hawaii, Manoa
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Instructor: Sasa Junuzovic
Yanal Alahmad Java Workshop Yanal Alahmad
Chapter 5: Control Structures II
Java Programming: Guided Learning with Early Objects
Chapter 4 – Control Structures Part 1
SELECTION STATEMENTS (1)
INPUT STATEMENTS GC 201.
Control Statement Examples
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Instructor: Prasun Dewan
CET 3640 – Lecture 2 Java Syntax Chapters 2, 4, 5
Building Java Programs
Building Java Programs
Chapter 4 - Control Structures: Part 1
Building Java Programs
Repetition Statements
LCC 6310 Computation as an Expressive Medium
Control Statements:.
Presentation 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”) Statement Statement List Statement... Statement List Statement... Statement Linear Statement List Stmt Statement Stmt Branching Statement List Stmt Statement Stmt Looping

Removing Training Wheels Text Editor ALoanPair Source Code creates Java Compiler reads ALoanPair Object (Byte) Code creates Java Interpreter ALoanPair Instance getTotalLoan() instantiates calls ObjectEditor main calls, Main Class Main Class Object (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 arguments main 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()

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

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) readCarLoanreadHouseLoanprint(LoanPair)pause readInt

Class-Level Decomposition Monolithic Main Class (Loan User Interface and Loan Computation) Object Editor Programmer- defined Class (A Loan Pair) Driver (ALoanPairDriver)

Class-Level Decomposition main print (Loan) readCarLoanreadHouseLoanprint(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 ( ) else

If-Else Statement true false

Compound Statement public 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 ( ) ;

if Statement true false

Nested if-else public 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-Else 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-Else

Looping printHello(2) hello printHello(3) 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 ( ) ; while ( ) ;

if Statement true false

while Statement true false

while loop true false

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 loan sumLoan = ALoan.add(sumLoan, loan1); loan1 = readLoan(); // 4th loan sumLoan = ALoan.add(sumLoan, loan1); print (sumLoan);

More Space Efficient Adding of Fixed Number of Loans Loan sumLoan = readLoan(); //first loan Loan nextLoan = readLoan(); //second loan sumLoan = Aloan.add(nextLoan, sumLoan); nextLoan = readLoan(); // 3rd loan sumLoan = ALoan.add(sumLoan, nextLoan); nextLoan = readLoan(); // 4th loan sumLoan = ALoan.add(sumLoan, nextLoan); print (sumLoan);

More Space Efficient Adding of Variable Number of Loans Loan sumLoan = readLoan(); //first loan Loan nextLoan = readLoan(); //second loan sumLoan = Aloan.add(nextLoan, sumLoan); nextLoan = readLoan(); // 3rd loan sumLoan = 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); InputResult 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 Identity result nextVal read first value read other values Binary folding function !isSentinel(nextVal)

Generalized Folding of a Sentinal-Terminated List a1a1 f f f anan a3a3 a2a2 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 Solution Loan, 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 function nextLoan = readLoan(); // read next list value } print (sumLoan); // print value