An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 7 : Building a Text-based.

Slides:



Advertisements
Similar presentations
Chapter 8 Testing a class. This chapter discusses n Testing in general. n Testing a single class. n Test plans. n Building a test system.
Advertisements

An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 16: Stream I/O.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
03 Data types1June Data types CE : Fundamental Programming Techniques.
Evan Korth Scanner class Evan Korth NYU. Evan Korth Java 1.5 (5.0)’s Scanner class Prior to Java 1.5 getting input from the console involved multiple.
Scanner Pepper With credits to Dr. Siegfried. The Scanner Class Most programs will need some form of input. At the beginning, all of our input will come.
Chapter 2: Java Fundamentals Input and Output statements.
1 TCSS 143, Autumn 2004 Lecture Notes Review. 2 Computer programming computers manipulate data data is often categorized into types numbers (integers,
Strings as objects Strings are objects. Each String is an instance of the class String They can be constructed thus: String s = new String("Hi mom!");
© 2006 Pearson Addison-Wesley. All rights reserved2-1 Console Input Using the Scanner Class Starting with version 5.0, Java includes a class for doing.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
1 Interactive Applications (CLI) Interactive Applications Command Line Interfaces Project 1: Calculating BMI Example: Factoring the Solution Reading for.
Introduction to Java Java SE 8 for Programmers Paul Deitel Harvey Deitel Deitel Developer Series 2014.
Chapter 2 Section 2.2 Console Input Using The Scanner CLASS Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska.
An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 7 : Building a Text-based.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Lesson 7: Improving the User Interface
Conditional If Week 3. Lecture outcomes Boolean operators – == (equal ) – OR (||) – AND (&&) If statements User input vs command line arguments.
CSC172 Intro Pepper. Goals Reminder of what a class is How to create and use classes How to design classes How to think in terms of objects How to comment.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Putting together a complete system Chapter 10. Overview  Design a modest but complete system  A collection of objects work together to solve a problem.
The Java Programming Language
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.
An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
Java Fundamentals 3 Input and Output statements. Standard Output Window Using System.out, we can output multiple lines of text to the standard output.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Input/Output in Java. Output To output to the command line, we use either System.out.print () or System.out.println() or System.out.printf() Examples.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Can we talk?. In Hello World we already saw how to do Standard Output. You simply use the command line System.out.println(“text”); There are different.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) public static void main(String[]
Textbook: Data Structures and the Java Collections Framework 3rd Edition by William Collins William Collins.
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
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.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
CHAPTER 5 GC 101 Input & Output 1. INTERACTIVE PROGRAMS  We have written programs that print console output, but it is also possible to read input from.
Introduction to Computing Concepts Note Set 12. Writing a Program from Scratch public class SampleProgram1 { public static void main (String [] args)
An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 8: Putting a System Together.
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
Keyboard and Screen I/O (Input/Output). Screen Output  System.out is an object that is part of the Java language. (Don’t worry yet about why there is.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Scanner Review Java Foundations: Introduction to Programming and Data Structures.
Interactive Programs Programs that get input from the user 1 In PowerPoint, click on the speaker icon then click the "Play" button to hear the narration.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
Introduction to programming in java
Input/Output.
TemperatureConversion
CSC1401 Input and Output (and we’ll do a bit more on class creation)
Objectives You should be able to describe: Interactive Keyboard Input
Yanal Alahmad Java Workshop Yanal Alahmad
CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II
Java Programming: From Problem Analysis to Program Design, 4e
INPUT STATEMENTS GC 201.
CSS 161 Fundamentals of Computing Introduction to Computers & Java
Introduction to Classes and Methods
Chapter 2: Basic Elements of Java
Introduction to Computing Using Java
Building Java Programs
Chapter 2: Java Fundamentals
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
Reading Input and Scanner Class
Presentation transcript:

An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 7 : Building a Text-based user interface.

1May 2004Chapter 7 Objectives ñAfter studying this chapter you should understand the following: ñindependence of servers from clients; ñlikeliness of the user interface to change; ñi/o streams; ñstructure of a simple text-based user interface; ñpurpose and structure of a while loop; ñhow existing classes can be composed to define a new class.

2May 2004Chapter 7 Objectives ñAlso, you should be able to: ñuse input/output objects to read and write data; ñbuild a simple text-based user interface; ñuse and trace a basic while statement; ñdefine classes whose implementations contain other classes as components.

3May 2004Chapter 7 Relating User-interface and Model ñModel: objects that solve problem at hand. ñUser interface: interacts with user, getting input from user, and giving output to user, reporting on status of model. ñFlexibility in design: identifying these as separate subsystems.

4May 2004Chapter 7 Stream-based I/O ñData streams: sequence of bytes. ñcharacter stream: sequence of characters ñ input stream: stream is a source of data for an application. ñoutput stream: stream is application destination (or sink).

5May 2004Chapter 7 Standard Input and Output streams standard output: characters to display

6May 2004Chapter 7 Writing standard output  System.out : provides methods for writing to standard output. public void println (String s) Write specified String to standard output and then terminate the line. public void print (String s) Write the specified String to standard output. public void println () Terminate current line by writing line terminator to standard output. public void flush () Flush stream: write buffered output to standard output and flush that stream.

7May 2004Chapter 7 Input : java.util.Scanner ñScanner ñreads characters from a character input stream. ñInput stream specified when Scanner is created. public Scanner (InputSource source) Create a Scanner to read from specified source. ñInput source: ñAssume characters are keyed from keyboard.  Use System.in

8May 2004Chapter 7 Input : java.util.Scanner ñTo create a Scanner reading from System.in ñ import java.util.Scanner Scanner input = new Scanner(System.in); Create a Scanner to read from specified source. ñScanner ñSees input as a sequence of tokens separated by white space. ñWhite space: spaces, tabs, line terminators, … ñSkips all white space before a token.

9May 2004Chapter 7 Input : java.util.Scanner ñScanner ñSees input as a sequence of tokens separated by white space. ñWhite space: spaces, tabs, line terminators, … ñIf user keys in: (  means space)  23  -34  5ab  c?  token

10May 2004Chapter 7 Input : java.util.Scanner ñGiven the data input stream:  23  -34  5ab  c?  token ñTokens can be read in using the methods: public String next() public boolean nextBoolean() public int nextInt() public double nextDouble()

11May 2004Chapter 7 Input : java.util.Scanner  Need 4 invocations of next () to read whole line:  23  -34  5ab  c?  token  Invoking next () will return tokens as strings: String one = input.next(); // one contains “23” String two = input.next(); // two contains “-34” String three = input.next(); // three contains “5ab” String four = input.next(); // four contains “c?”  next () is a query : returns a String token.  next () is a command: changes state of Scanner

12May 2004Chapter 7 Input: java.util.Scanner ñIf there are no tokens in the input stream, it will wait until user keys in a line with non- blank characters.  An input stream can be closed with the command close (). ñIf an input stream is closed or terminated attempting to read it will fail.

13May 2004Chapter 7 Input: java.util.Scanner ñThe methods  nextBoolean ()  nextInt ()  nextDouble () ñHave preconditions: token of form specified by method used, otherwise fails. ñTo verify these preconditions use:  hasNextBoolean ()  hasNextInt ()  hasNextDouble ()

14May 2004Chapter 7 Input: java.util.Scanner ñAfter reading some input tokens, you can skip the rest of the input tokens in the current line with the method: public String nextLine() advances past the current line and returns any input that was skipped excluding the’ line terminator.

15May 2004Chapter 7 Building an interface for Rectangle ñBuild an interface that let’s user specify dimensions of the Rectangle and ask for property to be displayed. class RectangleTUI A simple text-based interface for Rectangles. public RectangleTUI () Create a new RectangleTUI instance. public void start () Run the interface.

16May 2004Chapter 7 Building an interface for Rectangle  Application creates interface and executes start : public class RectangleExample { public static void main (String[] argv) { (new RectangleTUI()).start(); }

17May 2004Chapter 7 Building an interface for Rectangle ñInstance variables are initialized in constructor: ñRectangleTUI properties: private Rectangle rectangle; // the model private Scanner in; //standard input public RectangleTUI () { this.rectangle = null; this.in = new Scanner(System.in); }

18May 2004Chapter 7 Building an interface for Rectangle ñTo get Rectangle dimensions from user: private void createRectangle () Create a new Rectangle with user-provided dimensions. Uses readIntWithPrompt to get dimensions from user. private int readIntWithPrompt (String prompt) { System.out.print(prompt); System.out.flush(); int input = in.nextInt(); in.nextLine(); return input; }

19May 2004Chapter 7 Building an interface for Rectangle private void createRectangle () { int length; int width; length = readIntWithPrompt( "Rectangle length (a non-negative integer): "); width = readIntWithPrompt( "Rectangle width (a non-negative integer): "); this.rectangle = new Rectangle(length,width); }

20May 2004Chapter 7 Building an interface for Rectangle ñRectangleTUI is a client of Rectangle. ñConstructor creates an instance of Rectangle using input values from user. ñBut, Rectangle has pre-conditions to keep:  User may enter negative values for length or width. public Rectangle (int length, int width) Create a new Rectangle with specified length and width. require: length >= 0 && width >= 0

21May 2004Chapter 7 While statement condition true false statement END BEGIN while ( condition ) statement

22May 2004Chapter 7 Re-implementing createRectangle private void createRectangle () { //initialize to insure at least one execution of loops: int length = -1; int width = -1; while (length < 0) length = readIntWithPrompt( "Rectangle length (a non-negative integer): "); while (width < 0) width = readIntWithPrompt( "Rectangle width (a non-negative integer): "); // assert: length >=0 && width >= 0 this.rectangle = new Rectangle(length,width); }

23May 2004Chapter 7 Building an interface for Rectangle private void displayMenu () Display the menu to the user. private void executeChoice (int choice) Perform the indicated action, and display results to the user.

24May 2004Chapter 7 Building an interface for Rectangle ñName operation choices with identifiers: private static final int LENGTH = 1; private static final int WIDTH = 2; private static final int AREA = 3; private static final int PERIMETER = 4; private static final int NEW = 5; private static final int EXIT = 0; private static final int NO_CHOICE = -1;

25May 2004Chapter 7 Building an interface for Rectangle public void start () { createRectangle(); int choice = NO_CHOICE; while (choice!= EXIT) { displayMenu(); choice= readIntWithPrompt("Enter choice: "); executeChoice(choice); }

26May 2004Chapter 7 Building an interface for Rectangle private void displayMenu () { System.out.println(); System.out.println("Enter number denoting action to perform:"); System.out.println("Display length " + LENGTH); System.out.println("Display width " + WIDTH); System.out.println("Display area " + AREA); System.out.println("Display perimeter " + PERIMETER); System.out.println("Create new rectangle " + NEW); System.out.println("Exit " + EXIT); }

27May 2004Chapter 7 Building an interface for Rectangle private void executeChoice (int choice) { System.out.println(); if (choice == LENGTH) System.out.println("Length is " + rectangle.length()); else if (choice == WIDTH) System.out.println("Width is " + rectangle.width()); else if (choice == AREA) System.out.println("Area is " + rectangle.area()); else if (choice == PERIMETER) System.out.println("Perimeter is " + rectangle.perimeter()); else if (choice == NEW) createRectangle(); else if (choice == EXIT) System.out.println("Goodbye."); else System.out.println(choice + " is not valid."); }

28May 2004Chapter 7 Using composition ñBuild an application that lets a user access a “locked oracle.” ñuser can get a fortune from oracle only by providing correct key. ñUse classes CombinationLock and Oracle. ñCreate two new classes, ñone modeling a locked oracle, and ñother defining user interface.

29May 2004Chapter 7 Using composition public class Oracle A dispenser of fortunes. An Oracle gives a fortune only if it is awake; normal sequence of actions is: wake Oracle; get fortune; put the Oracle back to sleep. public Oracle () Create new Oracle. This Oracle is initially asleep. ensure: !this.isAwake() public boolean isAwake () This Oracle is awake. public String fortune () The prophecy currently seen by this Oracle. require: this.isAwake() public void awaken () Wake this Oracle. Oracle will divine a fortune when it wakes. public void sleep () Put this Oracle to sleep.

30May 2004Chapter 7 Using composition public class LockedOracle A keyed dispenser of fortunes. A LockedOracle will give a fortune only if the correct key is provided. A LockedOracle must be told to conjure a fortune before the fortune can be retrieved. public static final String NO_FORTUNE String indicating no fortune has been conjured. public LockedOracle (int key) Create new LockedOracle with the specified key. require: 0 <= key && key <= 999 public String fortune () The prophecy currently seen by this LockedOracle. If a fortune has not been conjured, the String NO_FORTUNE is returned. public void conjureFortune (int keyToTry) Prophesy. This LockedOracle will make a prophecy only if the correct key is presented. require: 0 <= keyToTry && keyToTry <= 999

31May 2004Chapter 7 Using composition  Composition: process of defining a new class by putting together existing classes. ñAn instance of the new class, the composite, references instances of the existing classes, its components.

32May 2004Chapter 7 Implementing LockedOracle ñLockedOracle class defined to be a composite, with CombinationLock and Oracle components.

33May 2004Chapter 7 Implementing LockedOracle ñInstance variables are initialized in constructor: private CombinationLock lock; private Oracle oracle; private String fortune; //current prophesy public static final String NO_FORTUNE = "Sorry, no fortune for you."; public LockedOracle (int key) { lock = new CombinationLock(key); lock.close(); oracle = new Oracle(); fortune = NO_FORTUNE; }

34May 2004Chapter 7 Implementing LockedOracle  Command conjureFortune first attempts to open lock, and wakes oracle only if it succeeds: public String fortune () { return this.fortune; } public void conjureFortune (int keyToTry) { lock.open(keyToTry); if (lock.isOpen()) { oracle.awaken(); fortune = oracle.fortune(); oracle.sleep(); lock.close(); } else fortune = NO_FORTUNE; }

35May 2004Chapter 7 Implementing the User interface class LockedOracleTUI A simple text-based interface for a LockedOracle. public LockedOracleTUI (LockedOracle oracle) Create a new interface for the specified LockedOracle. public void start () Run the interface.

36May 2004Chapter 7 Implementing the User interface  Application creates an oracle and an interface, and executes interface’s start method: public class OracleExample { public static void main (String[] argv) { LockedOracle oracle = new LockedOracle(123); LockedOracleTUI ui = new LockedOracleTUI(oracle); ui.start() } }

37May 2004Chapter 7 Implementing the User interface ñInstance variables and constructor. private LockedOracle oracle; private Scanner in; public LockedOracleTUI (LockedOracle oracle) { this.oracle = oracle; this.in = new Scanner(System.in); }

38May 2004Chapter 7 Implementing the User interface ñSpecify private helper methods: private boolean readYes (String prompt) Read a yes or no response from the user. Return true if user keys “yes.” private int readKey (String prompt) Read and return a legal key. ensure: 0 <= this.readKey() && this.readKey() <= 999

39May 2004Chapter 7 Implementing the User interface public void start () { String fortune; boolean goOn = true; while (goOn) { goOn = readYes("Fortune? (Key yes or no): "); if (goOn) { int key = readKey("Enter key (0-999): "); oracle.conjureFortune(key); fortune = oracle.fortune(); System.out.println(fortune); System.out.println(); } System.out.println("Good-bye."); }

40May 2004Chapter 7 Summary ñBuilt a simple text-based user interface. ñWe reviewed the relationship between client and server: ñ a client is dependent on its server, ña server is independent of its client.

41May 2004Chapter 7 Summary ñIn designing a system, it is preferable to make stable components independent of those likely to require change. ñSince user interface is considerably less stable than model, we favor designs in which the user interface acts as client to the model. ñIn cases where model must collaborate with the user interface, need to minimize interface for this collaboration.

42May 2004Chapter 7 Summary ñ Introduced i/o streams. ñA stream is a sequence of bytes, sometimes viewed as characters, to which an application can append data (an output stream) or from which an application can read data (an input stream). ñJava has an extensive library of classes to deal with streams. ñUse only basic functionality  from the predefined object System.out for output,  Scanner class from java.util package for input.

43May 2004Chapter 7 Summary ñ Presented two simple applications with their text- based user interfaces.  Introduced while statement or while-loop : a Java construct that specifies a sequence of actions to be repeated until a condition fails to hold.

44May 2004Chapter 7 Summary ñ In design of LockedOracle composed existing classes to construct a new class. ñThe relation between a composite class and its component classes is called the has-a relation. ñLockedOracle class wraps Oracle, adapting its specification to that required by the system: the adapter pattern.