Java Programming, 3e Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.

Slides:



Advertisements
Similar presentations
Topics Introduction Types of Errors Exceptions Exception Handling
Advertisements

Chapter 8 Improving the User Interface
Java Programming, 3e Concepts and Techniques Chapter 3 Section 63 – Manipulating Data Using Methods – Day 2.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Microsoft VB 2005: Reloaded, Advanced Chapter 5 Input Validation, Error Handling, and Exception Handling.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
Java review and more. Class Header  Public class Welcome  Case sensitive  Body of the class must be enclosed by braces.
CS 178: Programming with Multimedia Objects Aditya P. Mathur Professor of Computer Sciences Purdue University, West Lafayette Sept 9, 2004 Last update:
Java Programming, 3e Concepts and Techniques Chapter 5 Arrays, Loops, and Layout Managers Using External Classes.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 11 Exception Handling and Event Handling.
Java Programming, 3e Concepts and Techniques Chapter 3 Manipulating Data Using Methods.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
CSC110 Fall Chapter 5: Decision Visual Basic.NET.
Chapter 7 Improving the User Interface
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
Java Programming, 2E Introductory Concepts and Techniques Chapter 2 Creating a Java Application and Applet.
Java Programming, 2E Introductory Concepts and Techniques Chapter 3 Manipulating Data Using Methods.
Chapter 12: Exception Handling
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
Java Programming, 3e Concepts and Techniques Chapter 2 - Part 2 Creating a Java Application and Applet.
Java Programming, 3e Concepts and Techniques Chapter 3 Section 62 – Manipulating Data Using Methods – Day 1.
Java Programming, 3e Concepts and Techniques Chapter 3 Section 65 – Manipulating Data Using Methods – Java Applet.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 6 Decisions and Conditions.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Java Programming, Second Edition Chapter Five Input and Selection.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
Flow of Control Part 1: Selection
Introduction to Exception Handling and Defensive Programming.
Visual Basic.NET BASICS Lesson 5 Exponentiation, Order of Operations, and Error Handling.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
© 2006 Pearson Education 1 More Operators  To round out our knowledge of Java operators, let's examine a few more  In particular, we will examine the.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
JavaScript, Fourth Edition
Java Programming, 2E Introductory Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
1 Class 6. 2 Objectives Objectives Identify, declare, and use primitive data types Use the System class to create data streams Use the Scanner class of.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Creating a Java Application and Applet
Error Handling Tonga Institute of Higher Education.
Chapter 4 Introduction to Control Statements
Programming Logic and Design Fourth Edition, Comprehensive Chapter 14 Event-Driven Programming with Graphical User Interfaces.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Enhanced Car Payment Calculator Application Introducing Exception Handling.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
A First Book of C++ Chapter 4 Selection.
“Form Ever Follows Function” Louis Henri Sullivan
Java Programming: Guided Learning with Early Objects
Exception Handling Chapter 9.
Decision Making and Repetition with Reusable Objects
Part B – Structured Exception Handling
Exception Handling and Event Handling
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
Java Statements B.Ramamurthy CS114A, CS504 4/23/2019 BR.
Presentation transcript:

Java Programming, 3e Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects

Chapter 4: Decision Making and Repetition with Reusable Objects 2 Chapter Objectives Design a program using methods Code a selection structure to make decisions in code Describe the use of the logical AND, OR, and NOT operators Define exceptions and exception handling

Chapter 4: Decision Making and Repetition with Reusable Objects 3 Chapter Objectives Code a try statement and a catch statement to handle exceptions Create a user-defined method Code a repetition structure using the while statement Write a switch statement to test for multiple values in data

Chapter 4: Decision Making and Repetition with Reusable Objects 4 Chapter Objectives Format numbers using a pattern and the format() method Construct a Color object Use a Checkbox and a CheckboxGroup in the user interface

Chapter 4: Decision Making and Repetition with Reusable Objects 5 Introduction Control structures alter the sequential execution of code –Selection structure –Repetition structure User-defined methods break tasks into reusable sections of code Exception handling in Java allows for the testing of valid and accurate input

Chapter 4: Decision Making and Repetition with Reusable Objects 6 The Sales Commission Program Calculate sales commission for agents in a travel agency Coded as a console application and an applet Input –The user chooses from three types of commission codes The commission code identifies the type of sale and the commission rate –The user enters a sales amount Calculate commission and display output

Chapter 4: Decision Making and Repetition with Reusable Objects 7

8 Program Development Problem analysis –Each user decision corresponds to a program task –Develop and test each task before adding it to the program Design the solution –Design storyboards for the two user interfaces Program design –Design a flowchart consisting of required methods –Write related pseudocode for each method Validate Design

Chapter 4: Decision Making and Repetition with Reusable Objects 9

10 Coding the Program Code the program using program stubs –Stubs are incomplete portions of code that serve as a template or placeholder for later code –Stubs allow ease in debugging through incremental compilation and testing Import java.swing.JOptionPane Import java.text.DecimalFormat –Formats decimal output into Strings Declare variables Compile and test the program stub

Chapter 4: Decision Making and Repetition with Reusable Objects 11 Coding the Program

Chapter 4: Decision Making and Repetition with Reusable Objects 12 Writing Methods A program with modules allows for clarity, reusability, and refinement The code for each module can be separated into programmer-defined methods The main() method transfers execution to the methods through a call statement The called method returns control to its caller with the return statement or the ending brace –The return statement returns any required data back to the calling method

Chapter 4: Decision Making and Repetition with Reusable Objects 13

Chapter 4: Decision Making and Repetition with Reusable Objects 14 The if…else Statement Single: line 30, line 31 Block: lines 15-27, lines 19-20, lines Nested: lines 17-26, lines 30-31

Chapter 4: Decision Making and Repetition with Reusable Objects 15

Chapter 4: Decision Making and Repetition with Reusable Objects 16 Testing with an if statement Testing a single condition –if (answer == null) –if (!done) Testing multiple conditions –if ((gender == “male”) && (age >= 18)) –if ((age 65)) –AND and OR expressions evaluate the right operand only if the left operand is not sufficient to decide the condition

Chapter 4: Decision Making and Repetition with Reusable Objects 17 Exception Handling An exception is an event resulting from an erroneous situation which disrupts normal program flow Exception handling is the concept of planning for possible exceptions by directing the program to deal with them gracefully, without terminating Three kinds of exceptions –I/O –Run-time –Checked The compiler checks each method to ensure each method has a handler

Chapter 4: Decision Making and Repetition with Reusable Objects 18 Handling Exceptions The try statement identifies a block of statements that may potentially throw an exception The throw statement transfers execution from the method that caused the exception to the handler –Transfers execution to the catch statement if the throw is placed within a try statement The catch statement identifies the type of exception being caught and statements to describe or fix the error The finally statement is optional and is always executed regardless of whether an exception has taken place –Placed after the catch statement

Chapter 4: Decision Making and Repetition with Reusable Objects 19

Chapter 4: Decision Making and Repetition with Reusable Objects 20

Chapter 4: Decision Making and Repetition with Reusable Objects 21 Catch an exception Throw an exception

Chapter 4: Decision Making and Repetition with Reusable Objects 22 Throwing an Exception Compile the program after coding each method and call statement Run the program with correct input Run the program to test the exception handling with invalid input –Alphabetic data –Negative values –Null or zero values Verify that the user is allowed to reenter data Verify the program closes correctly

Chapter 4: Decision Making and Repetition with Reusable Objects 23 Repetition Structure

Chapter 4: Decision Making and Repetition with Reusable Objects 24 The getSales() method

Chapter 4: Decision Making and Repetition with Reusable Objects 25 The getCode() method

Chapter 4: Decision Making and Repetition with Reusable Objects 26 The Case Structure A type of selection structure that allows for more than two choices when the condition is evaluated Used when there are many possible, valid choices for user input The code evaluates the user choice with a switch statement and looks for a match in each case statement Each case statement contains a ending break statement which forces exit of the structure

Chapter 4: Decision Making and Repetition with Reusable Objects 27

Chapter 4: Decision Making and Repetition with Reusable Objects 28 The getComm() Method

Chapter 4: Decision Making and Repetition with Reusable Objects 29 Arguments and Parameters When a method is called, the calling method sends arguments; the called method accepts the values as parameters Different but related identifier names for the arguments and the parameters should be used for good program design –The variables are only visible in their respective methods Arguments and parameters for a called method and the calling statement must be of the same number, order, and data type

Chapter 4: Decision Making and Repetition with Reusable Objects 30 Formatting Numeric Output The DecimalFormat class formats decimal numbers into Strings for output Supports different locales, leading and trailing zeros, prefixes/suffixes, and separators The argument is a pattern, which determines how the formatted number should be displayed

Chapter 4: Decision Making and Repetition with Reusable Objects 31

Chapter 4: Decision Making and Repetition with Reusable Objects 32 The output() method

Chapter 4: Decision Making and Repetition with Reusable Objects 33 The finish() method Exits system when program completes successfully

Chapter 4: Decision Making and Repetition with Reusable Objects 34 Moving to the Web Create the host document to execute the applet

Chapter 4: Decision Making and Repetition with Reusable Objects 35 Coding an Applet Stub Enter general block comments Import java.awt.*, java.applet.*, java.awt.event.*, and java.text.DecimalFormat Implement the ItemListener interface to listen for the user choice on a Checkbox Code the method headers for the init() and the itemStateChanged() method –itemStateChanged() is an ItemListener method to process user choices Declare variables and construct a Color object

Chapter 4: Decision Making and Repetition with Reusable Objects 36

Chapter 4: Decision Making and Repetition with Reusable Objects 37 Making Decisions in Applets Use a CheckboxGroup to allow user choices

Chapter 4: Decision Making and Repetition with Reusable Objects 38 Constructing Applet Components Construct Labels for input and output Construct a CheckboxGroup for user options

Chapter 4: Decision Making and Repetition with Reusable Objects 39 Constructing Applet Components Add Labels and CheckboxGroup to the applet Add an ItemListener to each Checkbox component with the addItemListener() method Add color with the setForeground() and the setBackground() methods Set the insertion point with the requestFocus() method

Chapter 4: Decision Making and Repetition with Reusable Objects 40 The init() Method

Chapter 4: Decision Making and Repetition with Reusable Objects 41 Handling Exceptions Check for valid data when the itemStateChanged() method is triggered, which happens when the user clicks an option button

Chapter 4: Decision Making and Repetition with Reusable Objects 42 The getSales() Method Parse the data from the TextField and return a valid sales amount or throw an exception to the init() method

Chapter 4: Decision Making and Repetition with Reusable Objects 43 The getCode() Method Initialize the code to 0 Use nested if statements to assess the boolean state of the Checkboxes and return the code to init()

Chapter 4: Decision Making and Repetition with Reusable Objects 44 The getComm() Method Identical to the application Return the commission value to init()

Chapter 4: Decision Making and Repetition with Reusable Objects 45 The output() Method Send output to the Label using setText() Construct and use DecimalFormat, using the special character # to make a leading zero absent

Chapter 4: Decision Making and Repetition with Reusable Objects 46 The paint() Method Display a graphic

Chapter 4: Decision Making and Repetition with Reusable Objects 47 Compiling and Testing the Applet Compile the applet Execute the applet using AppletViewer Test exception handling by clicking an option button and then typing invalid data into the text box Verify the error message and the data clearing mechanisms Test all options with valid data Test in a browser window Document the applet interface and source code

Chapter 4: Decision Making and Repetition with Reusable Objects 48 Chapter Summary Design a program using methods Code a selection structure to make decisions in code Describe the use of the logical AND, OR, and NOT operators Define exceptions and exception handling

Chapter 4: Decision Making and Repetition with Reusable Objects 49 Chapter Summary Code a try statement and a catch statement to handle exceptions Create a user-defined method Code a repetition structure using the while statement Write a switch statement to test for multiple values in data

Chapter 4: Decision Making and Repetition with Reusable Objects 50 Chapter Summary Format numbers using a pattern and the format() method Construct a Color object Use a Checkbox and a CheckboxGroup in the user interface

Java Programming, 3e Concepts and Techniques Chapter 4 Complete