Lesson 7: Improving the User Interface

Slides:



Advertisements
Similar presentations
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Advertisements

Topics Introduction Types of Errors Exceptions Exception Handling
Chapter 8 Improving the User Interface
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
 2005 Pearson Education, Inc. All rights reserved Introduction.
The Print Formatting Statement … named printf. 2 Introduction to printf statements print and println statements don’t allow us to easily format output.
Java Programming, 3e Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
1 ICS103 Programming in C Lecture 3: Introduction to C (2)
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Input and Output The system console. In the beginning … When computers were relatively expensive and rare, most users interacted with a terminal –CRT.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Chapter 7 Improving the User Interface
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
Input/Output  Input/Output operations are performed using input/output functions  Common input/output functions are provided as part of C’s standard.
Fundamentals of Python: First Programs
 Pearson Education, Inc. All rights reserved Formatted Output.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Chapter 2 Overview of C Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
Chapter 2 - Algorithms and Design
Go Chapter 9 Improving the User Interface Section 1 - Query Controlled Programs Section 2 - Menu Controlled Programs Section 3 - Introduction to Try-Catch.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input.
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 2 Console Input and Output Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Console Input & Output CSS 161: Fundamentals of Computing Joe McCarthy 1.
Sahar Mosleh California State University San MarcosPage 1 System.out.println for console output System.out is an object that is part of the Java language.
Slides prepared by Rose Williams, Binghamton University Chapter 2 Console Input and Output.
Input, Output, and Processing
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Java Programming: Guided Learning with Early Objects
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.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
CMSC 202 Java Console I/O. July 25, Introduction Displaying text to the user and allowing the user to enter text are fundamental operations performed.
Lecture 2 Objectives Learn about objects and reference variables.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming, 2E Introductory Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
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.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Elementary Programming.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Chapter 3: Formatted Input/Output 1 Chapter 3 Formatted Input/Output.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Enhanced Car Payment Calculator Application Introducing Exception Handling.
28 Formatted Output.
Chapter 4 Assignment Statement
Chapter 3 Syntax, Errors, and Debugging
Objectives You should be able to describe: Interactive Keyboard Input
ICS103 Programming in C Lecture 3: Introduction to C (2)
Chapter 5: Control Structures II
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
Lecture 11 Objectives Learn what an exception is.
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Lesson 7: Improving the User Interface Updated for Java 1.5, (with additions and modifications by) Mr. Dave Clausen

Lesson 7: Improving the User Interface Construct a query-driven terminal interface. Construct a menu-driven terminal interface. Construct a graphical user interface. Format text, including numbers, for output. Handle number format exceptions during input.

Lesson 7: Improving the User Interface Vocabulary: Menu-driven program Query-controlled input Format specifiers Format String Format flags Exceptions

7.1 A Thermometer Class The demonstrations in this lesson involve converting temperatures between Fahrenheit and Celsius. To support these conversions we first introduce a Thermometer class Thermometer.java Thermometer.txt This class stores the temperature internally in Celsius; however, the temperature can be set and retrieved in either Fahrenheit or Celsius.

7.1 A Thermometer Class public class Thermometer {   private double degreesCelsius; public void setCelsius(double degrees){ degreesCelsius = degrees; } public void setFahrenheit(double degrees){ degreesCelsius = (degrees - 32.0) * 5.0 / 9.0; public double getCelsius(){ return degreesCelsius; public double getFahrenheit(){ return degreesCelsius * 9.0 / 5.0 + 32.0;

7.2 Repeating Sets of Inputs Another technique for handling repeating sets of inputs is called query controlled input. Before each set of inputs, after the first, the program asks the user if there are more inputs. Figure 7-1 shows an example:

7.2 Repeating Sets of Inputs

7.2 Repeating Sets of Inputs The program is implemented by means of two classes -- a class to handle the user interface and the Thermometer class. Following is pseudocode for the interface (client) class: instantiate a thermometer String doItAgain = “y” while (doItAgain equals “y” or “Y”){ read degrees Fahrenheit and set the thermometer ask the thermometer for the degrees in Celsius and display read doItAgain //The user responds with “y” or “n” }

7.2 Repeating Sets of Inputs The key to this pseudocode is the String variable doItAgain. This variable controls how many times the loop repeats. Initially, the variable equals “y”. As soon as the user enters a character other than "y" or "Y", the program terminates. Here is a complete listing of the interface class:

7.2 Repeating Sets of Inputs /* ConvertWithQuery.java ConvertWithQuery.txt Repeatedly convert from Fahrenheit to Celsius until the user signals the end. */ import java.util.Scanner;   public class ConvertWithQuery{ public static void main(String [] args) { Scanner reader = new Scanner(System.in); Thermometer thermo = new Thermometer(); String doItAgain = "y"; while (doItAgain.equals("y") || doItAgain.equals("Y")){ System.out.print("\nEnter degrees Fahrenheit: "); thermo.setFahrenheit(reader.nextDouble()); // Consume the trailing end of line reader.nextLine(); System.out.println("The equivalent in Celsius is " + thermo.getCelsius()); System.out.print("\nDo it again (y/n)? "); doItAgain = reader.nextLine(); }

7.2 Repeating Sets of Inputs In the previous code, observe that a String literal is enclosed within double quotes. doItAgain = reader.nextLine(); is used to read in the String "Y" and "y" are not the same, we need to check for either. while (doItAgain.equals("y") || doItAgain.equals("Y")) is used to check if the string is equal to “y” or “Y”. Strings cannot use = = to check for equivalence, you must use .equals

7.3 A Menu-Driven Conversion Program Menu-driven programs begin by displaying a list of options from which the user selects one. The program then prompts for additional inputs related to that option and performs the needed computations, after which it displays the menu again. Figure 7-2 shows how this idea can be used to extend the temperature conversion program.

7.3 A Menu-Driven Conversion Program

7.3 A Menu-Driven Conversion Program Following is the corresponding pseudocode and the source code: ConvertWithMenu.java ConvertWithMenu.txt instantiate a thermometer menuOption = 4 while (menuOption != 3){ print menu read menuOption if (menuOption == 1){ read fahrenheit and set the thermometer ask the thermometer to convert and print the results }else if (menuOption == 2){ read celsius and set the thermometer }else if (menuOption != 3) print "Invalid option" }

Generic Menu Driven Program Here is a generic Menu Driven Program that uses “Stub Programming” as generic place holders: MenuDrivenStub.java MenuDrivenStub.txt

7.4 Formatted Output with printf and format Java 5.0 includes method printf for formatting output. Requires format string and data values General form of printf:

7.4 Formatted Output with printf and format (cont.) Format string is a combination of literal string information and formatting information. Formatting information consists of one or more format specifiers. Begin with a ‘%’ character and end with a letter that indicates the format type Format.java Format.txt

7.4 Formatted Output with printf and format (cont.) Table 7-1: Commonly used format types

7.4 Formatted Output with printf and format (cont.) Symbol %n embeds an end-of-line character in a format string. Symbol %% produces literal '%' character. When compiler sees a format specifier, it attempts to match that specifier to an expression following the string. Must match in type and position

7.4 Formatted Output with printf and format (cont.) printf can justify text and produce tabular output. Format flags support justification and other styles. Table 7-2: Some commonly used format flags

The Formatter Class The full specification for the Formatter Class can be found at the following link: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax Formatting conversions apply to the following types: General, Character, Numeric, Date/Time, Percent, and Line Separator

7.4 Formatted Output with printf and format (cont.) Figure 7-3: Table of sales figures shown with and without formatting

7.4 Formatted Output with printf and format (cont.) To output data in formatted columns: Establish the width of each field. Choose appropriate format flags and format specifiers to use with printf. Width of a field that contains a double appears before the decimal point in the format specifier f

7.4 Formatted Output with printf and format (cont.) Table 7-3: Some example format strings and their outputs

7.4 Formatted Output with printf and format (cont.) Example 7.3: Display a table of names and salaries DisplayTable.java DisplayTable.txt

7.4 Formatted Output with printf and format (cont.) Formatting with the method String.format: Can be used to build a formatted string Use the same syntax as printf Returns a formatted string The difference is that resulting string is not displayed on the console window, but stored in a string variable

7.5 Handling Number Format Exceptions During Input If data are found to be invalid after input, the program can display an error message and prompt for the data again The program should detect and handle when a number is requested from the user, but the user enters a non-numerical value The Scanner methods nextInt() and nextDouble() will do this, but will crash the program with an error message

7.5 Handling Number Format Exceptions During Input (cont.) The try-catch construct allows exceptions to be caught and handled appropriately. Statements within try clause executed until an exception is thrown Exceptions sent immediately to catch clause Skipping remainder of code in try clause

7.5 Handling Number Format Exceptions During Input (cont.) If no statement throws an exception within the try clause, the catch clause is skipped. Many types of exceptions can be thrown. Catching an Exception object will catch them all. ConvertWithQueryException.java ConvertWithQueryException.txt

7.5 Handling Number Format Exceptions During Input (cont.) Here is the “try catch” statement rewritten without the use of a break statement in the while loop. ConvertWithQueryExceptionNoBreak.java ConvertWithQueryExceptionNoBreak.txt

Summary Terminal-based program: Program controls most of the interaction with the user The terminal input/output (I/O) interface can be extended to handle repeated sets of inputs. Query-based pattern Menu-driven pattern