CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 15: Nov 28-Dec 2, 2011 Aditya Mathur Department of Computer Science Purdue.

Slides:



Advertisements
Similar presentations
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Advertisements

Yoshi
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
1. 2 Examples for Exception?... An exception is an abnormal condition that arises in a code sequence at run time (Run time error). In other computer languages.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 13: Nov 14-18, 2011 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 8: Oct 10-14, 2011 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 4: September 12-16, 2011 Aditya Mathur/Tim Korb Department of Computer.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 13: Nov 15-19, 2010 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 16: Dec 6-10, 2010 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 9: Oct 17-21, 2011 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for the Final Lecture Dec 7, 2011 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 3: September 5-9, 2011 Aditya Mathur Department of Computer Science Purdue.
1 Why do we need exceptions? In C, return variables must be used to indicate errors: if((fd = fopen(path,...)) == -1){ if(errno==a){...} else if(errno==b){...}
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 1 What comes next? Recursion (Chapter 15) Recursive Data Structures.
Monday, 12/9/02, Slide #1 CS 106 Intro to CS 1 Monday, 12/9/02  QUESTIONS??  On HW #5 (Due 5 pm today)  Today:  Recursive functions  Reading: Chapter.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
CS 106 Introduction to Computer Science I 03 / 28 / 2008 Instructor: Michael Eckmann.
Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Exception Handling Recitation – 10/(23,24)/2008 CS 180 Department of Computer Science, Purdue University.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Exception Handling (Chapter 8) CS 180 Recitation - February 29, 2008 Department of Computer Science Purdue University.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 11: Oct 31-Nov 4, 2011 Aditya Mathur Department of Computer Science Purdue.
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions cs1043. Program Exceptions When a program detects an error, what should it do? – Nothing, simply allow the program to fail. – Implement a course.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
CE 221 Data Structures and Algorithms Chapter 4: Trees (Binary) Text: Read Weiss, §4.1 – 4.2 1Izmir University of Economics.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class 
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 11: Nov 1-5, 2010 Aditya Mathur Department of Computer Science Purdue University.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 14: Nov 21-25, 2011 Aditya Mathur Department of Computer Science Purdue.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 9: Oct 18-22, 2010 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 10: Oct 25-29, 2010 Aditya Mathur Department of Computer Science Purdue.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 10: Programming Exceptionally.
COP 3330 Notes 3/7. Today’s Topics Exceptions Abstract Classes.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Recursion Chapter What is recursion? Recursion occurs when a method calls itself, either directly or indirectly. Used to solve difficult, repetitive.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Creating and Modifying Text part 2
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Java Basics Exception Handling.
Exception Objects An exception is an abnormal condition that arises in a code sequence at rum time. Exception is a way of signaling serious problem.
CS Problem Solving and Object Oriented Programming Spring 2019
Java Programming: From Problem Analysis to Program Design, 4e
CS Problem Solving and Object Oriented Programming Spring 2019
Presentation transcript:

CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 15: Nov 28-Dec 2, 2011 Aditya Mathur Department of Computer Science Purdue University West Lafayette, IN, USA This Week: 11/ Exceptions 2.Recursion 3.Dynamic data structures

Readings and Exercises for Week 15 Readings: Chapter: 8.4, 12.1, 12.2, 12.3; 18.1, 18.8 Exercises: 8.6, 12.2, 12.3, 18.1, /28/2011 ©Aditya Mathur. CS 180. Fall Week 15 2

Announcements Project 5 due on Tuesday Dec 6, 11:59pm. Implement incrementally. Please DO attend the class on Monday Dec 5. Programming competition. Chief Guest Dr. Tim Korb. Details of Final Exam on Wednesday Dec 7. Please complete course evaluation. Thanks. Special class. Sunday Dec 11, pm. LWSN 3102AB 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 3

Average: 75.8 Median: 83 Std Dev: A+: 100/98 A: 97/94 A-: 93/90 B+: 89/87 B: 86/82 B-: 81/78 C+: 77/73 C: 72/67 C-: 66/56 D: 55/40 F: 39/0 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 4 Exam 2 Statistics

Exceptions 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 5

Exceptions An abnormal or unexpected condition during execution. When such a condition occurs, Java run time system does not always know how best to proceed and hence raises an exception. Some exceptions must be explicitly handled by the programmer. 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 6

Exception: Example 1 public class ExceptionExampleDiv0{ public static void main(String [] args){ int y=1, z=0; int x=y/z; } java.lang.ArithmeticException: / by zero at ExceptionExampleDiv0.main(ExceptionExampleDiv0.java:8) 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 7

Exception: Example 2 public class ExceptionExampleDiv0{ public static void main(String [] args){ int y=1, z=0; try{ int x=y/z; }catch(ArithmeticException e){ System.out.println(“Divide by zero:”+e); } } Divide by zero java.lang.ArithmeticException: / by zero Try-catch not required 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 8

Exception: Unchecked (or Error) Arise during runtime due to some programming error. Not flagged by the compiler. Programmer may choose to handle these. Not subject to Catch requirement. Examples: ArithmeticException ArrayIndexOutOfBounds NullPointerException 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 9

Exception: Example 3 public class ExceptionExampleFile{ public static void main(String [] args){ File f=new File("test.txt"); Scanner source=new Scanner(f); } 1 error found: File: /Users/apm/www/courses/CS180Fall2010/Notes/Programs/Exc eptions/ExceptionExampleFile.java [line: 8] Error: /Users/apm/www/courses/CS180Fall2010/Notes/Programs/Exc eptions/Except 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 10

Exception: Example 4 public class ExceptionExampleFile{ public static void main(String [] args){ File f=new File("test.txt"); try{ Scanner source=new Scanner(f); }catch(FileNotFoundException e){ System.out.println("File not found "+e); } File not found java.io.FileNotFoundException: test.txt (No such file or directory) 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 11

Exception: Checked exceptions These are subject to the catch requirement. Programmer is expected to write code to recover from these exceptions. Example: FileNotFoundException 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 12

Exception: try-catch try{ code where exception might occur; }catch(exception object){ code to handle exception } catch-block try-block A catch-block serves as an exception handler. 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 13

Exception: try-catch: multiple catch blocks try{ code where exception might occur; }catch(exception object){ code to handle exception; }catch(another exception object){ code to handle exception; } catch-block try-block Another catch- block 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 14

Exception: try-catch-finally try{ Code where exception might occur; }catch(exception object){ code to handle exception; }finally{ code to handle exception; } catch-block try-block finally-block finally-block always executes after the try-catch blocks (unless the program exits prior to the control arriving at the finally block). 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 15

Exception: Not handled public ExceptionTest(){ Scanner s=new Scanner(new File (“DoesNotExist”)); } Error: /Users/apm/www/courses/CS180Fall2011/Notes/Programs/Recur sion/Tree/ExceptionTest.java:7: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 16

Exception: Throwing public ExceptionTest() throws Exception{ Scanner s=new Scanner(new File (“DoesNotExist”)); } This will compile…. BUT… 11/28/2011 ©Aditya Mathur. CS 180. Fall Week A method…NOT a class…can throw an Exception.

Exception: Throwing but not handling later public ExceptionTest() throws Exception{ Scanner s=new Scanner(new File (“DoesNotExist”); } Error: /Users/apm/www/courses/CS180Fall2011/Notes/Programs/Recur sion/Tree/ExceptionTest.java:11: unreported exception java.lang.Exception; must be caught or declared to be thrown… 11/28/2011 ©Aditya Mathur. CS 180. Fall Week public static void main(String [] arg){ new ExceptionTest(); }

Exception: Throwing but handling later public ExceptionTest() throws Exception{ Scanner s=new Scanner(new File (“DoesNotExist”); } 11/28/2011 ©Aditya Mathur. CS 180. Fall Week public static void main(String [] arg){ try{ new ExceptionTest(); }catch(Exception e){ }

Recursion 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 20

What is recursion? We say that a method is recursive, when it calls itself. This is known as direct recursion. Recursion is a technique to code functions (or methods) in Java. Indirect recursion occurs when a method is called, before it completes, by another method. Recursion is complementary to iteration. While solving a problem, you may choose to use either. 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 21

Example: Factorial !n= 1, if n=0 or 1 = 1*2*3*…*n; Definition: Iterative [n>=0] !n= 1, if n=0 or 1 = n*!(n-1), if n>1 Definition: Recursive [n>=0] Basis Recursion 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 22

Example: Factorial: Iterative method !n= 1, if n=0 or 1 = 1*2*3*…*n; otherwise Definition: Iterative [n>=0] public int factIter(int n){ if(n==0 || n==1) return 1; int prod=1; for (int i=2; i<=n; i++){ prod=prod*i; } return (prod); } !5=prod=1*2*3*4*5 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 23

Example: Factorial: Recursive method public int factRecur(int n){ if(n==0 || n==1){ return 1; }else{ return (n*factRecur(n-1)); } !n= 1, if n=0 or 1 = n*!(n-1), if n>1 Definition: Recursive [n>=0] factRecur(5)=5*factRecur(4)*factRecur(3)*factRecur(2)*factRecur(1) =5*factRecur(4)*factRecur(3)*factRecur(2)*1 =5*factRecur(4)*factRecur(3)*2*1 =5*factRecur(4)*3*2*1 =5*4*3*2*1 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 24

Recursion versus Iteration Iteration suffices for most problems that arise in practice. However, in some cases recursion allows compact and quick solution. An example follows. 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 25

Announcements Feast with faculty today at 6:30pm Ford Dining Hall. All are welcome. Project 4 grades are on Blackboard. If your submitted program was working but you received a low grade then please contact TA Julian Stephen. Programming competition: Round 2: Saturday 6pm. LWSN Three teams will be selected for the final round. 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 26

Towers of Hanoi: The problem Given: Three towers A, B, and C. A contains n discs arranged from bottom to top as shown below. Problem: Find a sequence of moves such that at the end of these moves all discs are in C. No larger disc should ever be on top of a smaller disk. Only one disk can be moved at a time from one tower to another. Only the top disc can be moved from a tower. ABC 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 27

Towers of Hanoi: Initial and final configurations ABC Initial configuration ABC Final configuration 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 28

Towers of Hanoi: Iterative solution Try this! This will be difficult but certainly worth a try. 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 29

Towers of Hanoi: Recursive solution What is a move? Only one disc can be moved from one tower to another. Hence we will write a move as: moveADisc (TA, TB); TA is the tower from where the top disc is moved and placed on top in tower TB. move (TA, TB, TC, n); This will move n discs from tower TA to tower TB via tower TC while ensuring the constraints. 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 30

Towers of Hanoi: Recursive solution: Visualization BCA Start 1 BCA 2 BCA 3 BCA 4 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 31

Towers of Hanoi: Recursive program: Live 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 32

Towers of Hanoi: Challenge! How many moves are required to move n discs from tower A to tower C? 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 33

Recursion and Dynamic data structures 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 34

Dynamic data structures Useful when size of the data structure is not known in advance. Useful for designing efficient algorithms. 11/28/2011 ©Aditya Mathur. CS 180. Fall Week Examples: Stack, Linked list, binary tree, etc. In Java: ArrayList, Vector Static data structure: Array

Tree (Binary) 11/28/2011 ©Aditya Mathur. CS 180. Fall Week Tree with one node (the root) Left link Right link Tree with a root linked to two other nodes. Left link Right link Another tree.

Tree: with data 11/28/2011 ©Aditya Mathur. CS 180. Fall Week Tree with one node (the root) 25 Left link Right link Tree with a root linked to two other nodes Left link Right link Another tree Do you see a pattern?

Tree: Binary search 11/28/2011 ©Aditya Mathur. CS 180. Fall Week Left link Right link Does x exist in the tree? boolean find(int x, Node root){ if(x is at the root) return true; if (x< value at the root) return find (x, root.leftLink); else return find(x, root.rightLink); }

Binary search tree: Creation 11/28/2011 ©Aditya Mathur. CS 180. Fall Week Add 39. This is greater than the number at the root. Hence add a new node to the right subtree Add 14. As this is less than the value at the root, add a new node to the left of the root. Left link Right link Add 25. Start with an empty tree and add a node. Set root to be this node. 25 Left and right links are null. Each data item exists exactly once in the tree.

Tree: Non-empty binary search tree 11/28/2011 ©Aditya Mathur. CS 180. Fall Week Has a root Each node has 0, 1, or 2 links. Links are generally termed as left and right links. Each node has a data item in it. Suppose that node n points to nodes n1 (left) and n2 (right). Then the data at node n1 is less than that at n and the data at node n2 is greater than that at node n.

Binary search tree creation: Exercise 11/28/2011 ©Aditya Mathur. CS 180. Fall Week What will a binary search tree look like after the following numbers are added in this sequence given: 5, 29, -4, 23, 99, 3?

Live demo: Tree creation and traversal. 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 42

Week 15: November 28-Dec 2, 2011 Hope you enjoyed this week! Questions? Contact your recitation instructor. Make full use of our office hours. 11/28/2011 ©Aditya Mathur. CS 180. Fall Week 15 43