CS1101X: Programming Methodology Recitation 5 Exceptions & Characters and Strings.

Slides:



Advertisements
Similar presentations
Exceptions Session 21. Memory Upload Creating Exceptions Using exceptions to control object creation and validation.
Advertisements

Java Programming Strings Chapter 7.
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 8 Exceptions and Assertions.
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
بسم الله الرحمن الرحيم CPCS203: Programming II. Objectives After you have read and studied this chapter, you should be able to –Improve the reliability.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions Chapter 18 Programs: DriverException2 DriverException TestAgeInputException.
Chapter Chapter 8 Exceptions and Assertions.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exception handling Dealing with life’s little surprises.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exceptions Handling.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exceptions and Assertions Animated Version.
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
TA: Nouf Al-Harbi NoufNaief.net :::
Ahmad Al-Rjoub Chapter 6 Exceptions CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
10 ThinkOfANumber program1July ThinkOfANumber program CE : Fundamental Programming Techniques.
1 Lab Session-VIII CSIT-121 Spring 2002 w Formatted Output w Call by Reference w Lab Exercises w File Handling w Lab Exercises.
CS1101X: Programming Methodology Recitation 2 Classes.
Introduction to Computer Programming Error Handling.
Fundamental concepts in Java. Lesson plan Variable declaration, assign statement & practice Design document & practice.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Chapter 6 – Repetition Statements : Objectives After you have read and studied this chapter, you should be able to Implement repetition control in a program.
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
Using Classes BCIS 3680 Enterprise Programming. Overview 2  Using Classes  Using premade classes for input and output  Display output: System, JOptionPane.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CS1101X: Programming Methodology Recitation 3 Control Structures.
CS1101X: Programming Methodology Recitation 1 Java Basics Numerical Data.
习 题 4.23 编写一个 applet ,读取一个矩形的边长,然后 用在 paint 方法中使用 drawString 方法画出用星组成 的空心矩形。程序应能画出边长从 1 到 20 的任何矩 形。
Java The Java programming language was created by Sun Microsystems, Inc. It was introduced in 1995 and it's popularity has grown quickly since A programming.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CS1101X: Programming Methodology Recitation 4 Design Issues and Problem Solving.
Exercise 1 Introduction to C# CIS Code the C# program to prompt the user to key in 12 integer values from the keyboard. If a value containing.
Introduction to Computing Concepts Note Set 15. JOptionPane.showMessageDialog Message Dialog Allows you to give a brief message to the user Can be used.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
Unit Testing Part 2: Drivers and Stubs
1 Class Chapter Objectives Use a while loop to repeat a series of statements Get data from user through an input dialog box Add error checking.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 11 So Many Paths … So Little Time.
Chapter 10 So Many Paths … So Little Time (Multiple-Alternative Selection Structures) Clearly Visual Basic: Programming with Visual Basic nd Edition.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exception Handling.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
Chapter 10 – Exception Handling
CS1101: Programming Methodology Recitation 7 – Exceptions
Computing with C# and the .NET Framework
Message, Input, Confirm, and Specialized Dialogs
Control Statement Examples
Introduction to Java Programming
Class Examples.
Exceptions one last time…
CIS 110: Introduction to Computer Programming
Presentation transcript:

CS1101X: Programming Methodology Recitation 5 Exceptions & Characters and Strings

CS1101X Recitation #52 Ch8AgeInputMain.java import javax.swing.*; import java.util.*; class Ch8AgeInputMain { public static void main( String[] args ) { GregorianCalendar today; int age, thisYear, bornYr, answer; AgeInputVer1 input = new AgeInputVer1( ); //no exception handling // AgeInputVer2 input = new AgeInputVer2( ); //first level exception handling // AgeInputVer3 input = new AgeInputVer3( ); //more exeption handling age = input.getAge("How old are you?"); today = new GregorianCalendar( ); thisYear = today.get(Calendar.YEAR); bornYr = thisYear - age; answer = JOptionPane.showConfirmDialog(null, "Already had your birthday this year?", "", JOptionPane.YES_NO_OPTION); if (answer == JOptionPane.NO_OPTION) bornYr--; JOptionPane.showMessageDialog(null, "You are born in " + bornYr); }

CS1101X Recitation #53 AgeInputVer1.java import javax.swing.*; class AgeInputVer1 { private static final String DEFAULT_MESSAGE = "Your age:"; public AgeInputVer1( ) { } public int getAge() { return getAge(DEFAULT_MESSAGE); } public int getAge(String prompt) { String inputStr = JOptionPane.showInputDialog(null, prompt); int age = Integer.parseInt(inputStr); return age; } No check.

CS1101X Recitation #54 AgeInputVer2.java import javax.swing.*; class AgeInputVer2 { // constant, constructor and getAge() omitted – same as version 1 public int getAge(String prompt) { String inputStr; int age; while (true) { inputStr = JOptionPane.showInputDialog(null, prompt); try { age = Integer.parseInt(inputStr); return age; // input okay so return the value } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "'" + inputStr + "' is invalid\n" + "Please enter digits only"); } What if user enters “nine”?

CS1101X Recitation #55 AgeInputVer3.java import javax.swing.*; class AgeInputVer3 { // constant, constructor and getAge() omitted – same as version 1 public int getAge(String prompt) { String inputStr; int age; while (true) { inputStr = JOptionPane.showInputDialog(null, prompt); try { age = Integer.parseInt(inputStr); if (age < 0) throw new Exception("Negative age is invalid"); return age; // input okay so return the value } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "'" + inputStr + "' is invalid\n" + "Please enter digits only"); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error: " + e.getMessage()); } What if user enters negative value?

CS1101X Recitation #56 AgeInputVer4.java (1/3) import javax.swing.*; class AgeInputVer4 { private static final String DEFAULT_MESSAGE = "Your age:"; private static final int DEFAULT_LOWER_BOUND = 0; private static final int DEFAULT_UPPER_BOUND = 99; private int lowerBound; private int upperBound; // default constructor public AgeInputVer4( ) throws IllegalArgumentException { setBounds(DEFAULT_LOWER_BOUND, DEFAULT_UPPER_BOUND); } // Contructs an age input with the specified lower and upper bounds. public AgeInputVer4(int low, int high) throws IllegalArgumentException { if (low > high) { throw new IllegalArgumentException( "Low (" + low + ") was " + "larger than high(" + high + ")"); } else setBounds(low, high); } Adding a valid range for age.

CS1101X Recitation #57 AgeInputVer4.java (2/3) public int getAge() throws Exception { return getAge(DEFAULT_MESSAGE); } // Inputs the age from an input dialog with the designated prompt public int getAge(String prompt) throws Exception { String inputStr; int age; while (true) { inputStr = JOptionPane.showInputDialog(null, prompt); try { age = Integer.parseInt(inputStr); if (age upperBound) throw new Exception("Input out of bound"); return age; // input okay so return the value } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "'" + inputStr + "' is invalid\n" + "Please enter digits only"); } Adding a valid range for age.

CS1101X Recitation #58 AgeInputVer4.java (3/3) // Sets the lower and upper bounds of the input private void setBounds(int low, int high) { lowerBound = low; upperBound = high; }

CS1101X Recitation #59 AgeInputVer5.java Programmer-defined exceptions. Essentially the same as AgeInputVer4.java except that now the getAge method throws an AgeInputException. The AgeInputException is defined by the programmer. // Inputs the age from an input dialog with the designated prompt public int getAge(String prompt) throws AgeInputException { String inputStr; int age; while (true) { inputStr = JOptionPane.showInputDialog(null, prompt); try { age = Integer.parseInt(inputStr); if (age upperBound) throw new AgeInputException("Input out of bound", lowerBound, upperBound, age); return age; // input okay so return the value } // code omitted }

CS1101X Recitation #510 AgeInputException.java (1/2) class AgeInputException extends Exception { private static final String DEFAULT_MESSAGE = "Input out of bounds"; private int lowerBound; // lower bound of age input private int upperBound; // upper bound of age input private int value; // entered value public AgeInputException(int low, int high, int input) { this(DEFAULT_MESSAGE, low, high, input); } public AgeInputException(String msg, int low, int high, int input) { super(msg); if (low > high) { throw new IllegalArgumentException(); } lowerBound = low; upperBound = high; value = input; }

CS1101X Recitation #511 AgeInputException.java (2/2) // Returns the lower bound of the age input public int lowerBound() { return lowerBound; } // Returns the upper bound of the age input public int upperBound() { return upperBound; } // Returns the entered value public int value() { return value; }

CS1101X Recitation #512 Characters and Strings Exercise 17 (page 537)  Write an application NumVowels.java that reads in a sentence and displays the count of individual vowels in the sentence. Use any output routine of your choice to display the result in this format. Count both the lowercase and uppercase vowels. Vowel counts for the sentence Mary Had A Little Lamb. Number of 'a': 4 Number of 'e': 1 Number of 'i': 1 Number of 'o': 0 Number of 'u': 0

CS1101X Recitation #513 Characters and Strings Exercise 11 (page 536)  Write a program ReverseCase.java that reads a sentence and prints out the sentence with all uppercase letters changed to lowercase and all lowercase letters changed to uppercase. Enter sentence: Mary Had A LiTTle LaMb. mARY hAD a lIttLE lAmB.

CS1101X Recitation #514 End of Recitation #5