Object-based Scanning Redo the scanning solutions Monolithic, single class solutions –does UI and scanning No reuse of code.

Slides:



Advertisements
Similar presentations
J A V A SHASHI BHUSHAN. MAIN ISSUES Object Oriented Concepts Examples FAQs.
Advertisements

C OMP 110 A RRAYS Instructor: Jason Carter. 2 O UTLINE for loops Arrays.
C OMP 401 D YNAMIC D ISPATCH AND A BSTRACT M ETHODS Instructor: Prasun Dewan.
Comp 114 Foundations of Programming Instructor: Prasun Dewan.
Arrays –Collections (Set, Database, History) Inheritance –inheriting ancestor’s traits –inheriting benefactor’s assets –inheriting instance members( methods/variables)
Exceptions Problems with error reporting so far –Either ignored exceptions or terminated program on first error. –Error handling and regular code mixed.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
Scanning Scanning image for text. Scanning frequencies for radio stations. Finding words in a sentence Finding identifiers, operators, in a program char.
Exceptions Problems with error reporting so far –Either ignored exceptions or terminated program on first error. –Error handling and regular code mixed.
CS 225 Java Review. Java Applications A java application consists of one or more classes –Each class is in a separate file –Use the main class to start.
ObjectEditor Prasun Dewan Comp 114. ObjectEditor Automatic user-interface generation. You only write computation code Separate object to do I/O Main just.
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!");
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
Comp 114 Foundations of Programming Instructor: Prasun Dewan (Pr  sün Divän)
Object-based Scanning Redo the scanning solution Monolithic, single class solution –does UI and scanning No reuse of code Another scanning problem to.
March 2005Java Programming1. March 2005Java Programming2 Why Java? Platform independence Object Oriented design Run-time checks (fewer bugs) Exception.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Console Input. So far… All the inputs for our programs have been hard-coded in the main method or inputted using the dialog boxes of BlueJ It’s time to.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
C OMP 401 B ASICS O F S CANNING Instructor: Prasun Dewan (FB 150,
Java Arrays …………. Java Arrays …………. * arrays are objects in Java * arrays are objects in Java * an array variable is a reference * an array variable is.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 5 Loops.
Introduction to Programming G50PRO University of Nottingham Unit 8 : Methods 2 - Arrays Paul Tennent
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Case study Students. Array of objects Arrays can hold objects (ref to objects!) Each cell in an array of objects is null by default Sample: from student.
Chapter 4: Control Structures II
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.
Advanced Computer Science Lesson 4: Reviewing Loops and Arrays Reading User Input.
C OMP 401 A DVANCED G ENERICS Instructor: Prasun Dewan.
Java 1.5 The New Java Mike Orsega Central Carolina CC.
Java Arrays and Methods MIS 3023 Business Programming Concepts II The University of Tulsa Professor: Akhilesh Bajaj All slides in this presentation ©Akhilesh.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Chapter 3A Strings. Using Predefined Classes & Methods in a Program To use a method you must know: 1.Name of class containing method (Math) 2.Name of.
CSE 110 Review Session Hans Hovanitz, Kate Kincade, and Ian Nall.
Chapter 5 : Methods Part 2. Returning a Value from a Method  Data can be passed into a method by way of the parameter variables. Data may also be returned.
Vector program patterns Vectors contain many elements, so loops are common. Counted processing // Print the first 3 elements. for (int i = 0; i < 3; i++)
import java.util.Scanner; class myCode { public static void main(String[] args) { Scanner input= new Scanner(System.in); int num1; System.out.println(“Enter.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 4 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
Mid-Year Review. Coding Problems In general, solve the coding problems by doing it piece by piece. Makes it easier to think about Break parts of code.
I/O in java and Revision. 2 I/O in Java Many packages and libraries associated with Java provide sophisticated ways to input and output information, e.g.:
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Section 2.2 The StringLog ADT Specification. 2.2 The StringLog ADT Specification The primary responsibility of the StringLog ADT is to remember all the.
Yanal Alahmad Java Workshop Yanal Alahmad
COMPUTER 2430 Object Oriented Programming and Data Structures I
Chapter 6 More Conditionals and Loops
Chapter 5: Control Structures II
Repetition-Sentinel,Flag Loop/Do_While
Chapter 5: Control Structures II
SELECTION STATEMENTS (1)
Comp 401 Dynamic Dispatch and Virtual and Abstract Methods
Control Statement Examples
CSS161: Fundamentals of Computing
L3. Necessary Java Programming Techniques
L3. Necessary Java Programming Techniques
Recitation 10 November 3, 2011.
CIS 199 Final Review.
Building Java Programs
Java: Variables, Input and Arrays
A type is a collection of values
Presentation transcript:

Object-based Scanning Redo the scanning solutions Monolithic, single class solutions –does UI and scanning No reuse of code

Upper case printing package warmup; public class AnUpperCasePrinter { public static void main(String[] args){ if (args.length != 1) { System.out.println("Illegal number of arguments:" + args.length + ". Terminating program."); System.exit(-1); } System.out.println("Upper Case Letters:"); int index = 0; while (index < args[0].length()) { if (isUpperCase(args[0].charAt(index))) System.out.print(args[0].charAt(index)); index++; } System.out.println(); } public static boolean isUpperCase(char c) { return (c >= 'A') && (c <= 'Z'); }

Forward and reverse printing package warmup; public class AReverseUpperCasePrinter { static final int MAX_CHARS = 5; static char[] upperCaseLetters = new char[MAX_CHARS]; static int numberOfUpperCaseLetters = 0; public static void main(String[] args){ if (args.length != 1) { System.out.println("Illegal number of arguments:" + args.length + ". Terminating program."); System.exit(-1); } int index = 0; System.out.println("Upper Case Letters:"); while (index < args[0].length()) { if (isUpperCase(args[0].charAt(index))) { System.out.print(args[0].charAt(index)); storeChar(args[0].charAt(index)); } index++; } System.out.println(); printReverse(); }

Forward and reverse printing (contd.) public static void storeChar(char c) { if (numberOfUpperCaseLetters == MAX_CHARS) { System.out.println("Too many upper case letters. Terminating program. "); System.exit(-1); } upperCaseLetters[numberOfUpperCaseLetters] = c; numberOfUpperCaseLetters++; } public static void printReverse() { System.out.println("Upper Case Letters in Reverse:"); for (int index =numberOfUpperCaseLetters - 1; index >= 0; index--) { System.out.print(upperCaseLetters[index]); }

No reuse in Monolithic Solutions int index = 0; System.out.println("Upper Case Letters :");//token processing while (index < args[0].length()) { if (Character.isUpperCase(args[0].charAt(index);)) { System.out.print(args[0].charAt(index);); // token processing storeChar(args[0].charAt(index)); } index ++; } int index = 0; System.out.println("Upper Case Letters :");//token processing while (index < args[0].length()) { if (Character.isUpperCase(args[0].charAt(index);)) System.out.print(args[0].charAt(index)); // token processing index ++; }

Class Decomposition? Main Class

Division of Labor in Radio Scanning

?

Scanner Object calls Scanner User Main Class (Input & Output) Class Decomposition Scanner Class instantiate

BufferedReader Instance readLine() Scanner User Main Class (Input & Output) Class Decomposition BufferedReader instantiate

Scanner User-Scanner Object Interaction BufferedReader dataIn = new BufferedReader (new InputStreamReader( System.in)); int product = 1; // add input list terminated by a negative number while (true) { int num = Integer.parseInt (dataIn.readLine()); if (num < 0) break; product = product*num; } System.out.println (product);

Constructor parameters InputStreamReader takes System.in as parameter. BufferedReader takes InputStreamReader as parameter. In general, scanner takes object producing scanned stream as parameter.

BufferedReader Operations Line 1Line 2 Multi-line input stream Line stream dataIn.readLine()Line 1 dataIn.readLine()Line 2 dataIn.readLine()IOException

Scanner Interface? scanner.nextElement()token 1 scanner.nextElement()token 2 scanner.nextElement()ScannerException token 1token 2 Input stream Token Stream

Scanner Interface? scanner.nextElement()token 1 scanner.nextElement()token 2 scanner.hasMoreElements()false Input stream Token Stream token 1token 2 scanner.nextElement()???

Uppercase Scanner Interface? scanner.nextElement()‘J’ scanner.nextElement()‘F’ scanner.hasMoreElements()false JohnF.Kenndye token 1token 2token 3 scanner.nextElement()‘K’ scanner.nextElement()???

Enumeration Interfaces package enums; public interface CharEnumeration { public char nextElement(); public boolean hasMoreElements(); } package enums; public interface StringEnumeration { public String nextElement(); public boolean hasMoreElements(); } package ; public interface Enumeration { public nextElement(); public boolean hasMoreElements(); }

Using an Enumeration Interface public static void printChars (CharEnumeration charEnumeration) { while (charEnumeration.hasMoreElements()) System.out.print(charEnumeration.nextElement()); } JohnF.Kenndye token 1token 2token 3

Using an Enumeration Interface package main; import enums.CharEnumeration; import enums.AnUpperCaseEnumeration; public class UpperCasePrinter { public static void main (String args[]) { if (args.length != 1) { System.out.println("Illegal number of arguments:" + args.length + ". Terminating program."); System.exit(-1); } printUpperCase(args[0]); } public static void printUpperCase(String s) { System.out.println("Upper Case Letters:"); printChars (new AnUpperCaseEnumeration(s)); } public static void printChars (CharEnumeration charEnumeration) { while (charEnumeration.hasMoreElements()) System.out.print(charEnumeration.nextElement()); }

Implementing Scanner package enums; public class AnUpperCaseEnumeration implements CharEnumeration { … public AnUpperCaseEnumeration(String theString) {... } public boolean hasMoreElements() {... } public char nextElement() {...; } … }

Data Structure: Scanned String package enums; public class AnUpperCaseEnumeration implements CharEnumeration { String string; … public AnUpperCaseEnumeration(String theString) { string = theString;... } public boolean hasMoreElements() {... } public char nextElement() {...; } … }

Data Structure: marker JohnF.Kenndye nextElementPos string scanned partUnscanned part

hasMoreElements() JohnF.Kenndye string nextElementPos public boolean hasMoreElements() {... } true

hasMoreElements() JohnF.Kenndye string nextElementPos public boolean hasMoreElements() {... } true

hasMoreElements() JohnF.Kenndye string nextElementPos public boolean hasMoreElements() {... } false

hasMoreElements() JohnF.Kenndye string nextElementPos //return true if nextElementPos is beyond end of string; false otherwise public boolean hasMoreElements() {... }

hasMoreElements() JohnF.Kenndye string nextElementPos //return false if nextElementPos is beyond end of string; true otherwise public boolean hasMoreElements() { return nextElementPos < string.length(); }

nextElement() JohnF.Kenndye string nextElementPos public char nextElement() { }

nextElement() JohnF.Kenndye string nextElementPos //Assume nextElemPos is at start of next token or end of string when //method is called. //Method makes sure this is also true before returning. //returns next element if one exists public char nextElements() { }

nextElement() JohnF.Kenndye string nextElementPos //Assume nextElemPos is at start of next token or end of string when //method is called. //Method makes sure this is also true before returning. //returns next element if one exists public char nextElement() { } char retVal = string.charAt(nextElemPos) return retVal; while (!isUpperCase(string.charAt(nextElementPos))) nextElemPos++; Unexecuted Loop

nextElement() JohnF.Kenndye string nextElementPos //Assume nextElemPos is at start of next token or end of string when //method is called. //Method makes sure this is also true before returning. //returns next element if one exists public char nextElements() { } movePastCurrentToken(); char retVal = extractToken(); return retVal; skipNonTokenCharacters();

nextElement() JohnF.Kenndye string nextElementPos //Assume nextElemPos is at start of next token or end of string when //method is called. //returns next token if one exists public char extractToken() { } return string.charAt(nextElementPos);

movePastCurrentToken() //Assume nextElemPos is at start of next token or end of string when //method is called. //Moves past current token. public void movePastCurrentToken() { } nextElemPos++; JohnF.Kenndye string nextElementPos

skipNonTokenCharacters() JohnF.Kenndye string nextElementPos // keep advancing nextElementPos until we hit the next upper case public void skipNonTokenCharacters() { } while (! isUpperCase(string.charAt(nextElementPos))) nextElemPos++; StringIndexOutOfBounds

skipNonTokenCharacters() JohnF.Kenndye string nextElementPos // keep advancing nextElementPos until we hit the next upper case or go // beyond the end of the string. public void skipNonTokenCharacters() { } while (nextElementPos < string.length() && !Character.isUpperCase(string.charAt(nextElement Pos))) nextElemPos++; StringIndexOutOfBounds?short-circuit

Initialization johnF.Kenndye string nextElementPos String string; int nextElementPos = 0; public AnUpperCaseEnumeration(String theString) { } string = theString; skipNonTokenCharacters();

Complete Scanner package enums; public class AnUpperCaseEnumeration implements CharEnumeration { String string; int nextElementPos = 0; public AnUpperCaseEnumeration(String theString) { string = theString; skipNonTokenCharacters(); } public boolean hasMoreElements() { return nextElementPos < string.length();} public char nextElement() { char retVal = extractToken(); movePastCurrentToken(); skipNonTokenCharacters(); return retVal; } void movePastCurrentToken() {nextElementPos++;} void skipNonTokenCharacters() { while (nextElementPos < string.length() && !isUpperCase(string.charAt(nextElementPos))) nextElementPos++; } char extractToken() { return string.charAt(nextElementPos);} boolean isUpperCase (char c) { return c >= ‘A’ && c <= ‘Z’;} } constructor

Scanner Pattern package ; public class implements Enumeration { String string; int nextElementStart = 0; int nextElementEnd = ???; public AnUpperCaseEnumeration(String theString) { string = theString; skipNonTokenCharacters(); } public boolean hasMoreElements() { return nextElementStart < string.length();} public nextElement() { retVal = extractToken(tokenLength); movePastCurrentToken(tokenLength); skipNonTokenCharacters(); return retVal; } void movePastCurrentToken() {…}; void skipNonTokenCharacters() {…}; char extractToken() { …} }

AnUpperCaseEnumeration instance Class Decomposition AnUpperCaseEnumeration instantiate AnUppercasePrinter

AnUpperCaseEnumeration instance Class Decomposition AnUpperCaseEnumeration instantiate AReverseUpperCasePrinter

Reuse of Enumeration while (charEnumeration.hasMoreElements()) { char nextChar = charEnumeration.nextElement()); System.out.print(nextChar); storeChar(nextChar); } while (charEnumeration.hasMoreElements()) System.out.print(charEnumeration.nextElement());

Enumeration Vs Scanning public interface CharEnumeration { public char nextElement(); public boolean hasMoreElements(); } JohnF.Kenndye token 1token 2token 3

Enumeration without Scanning public interface CharEnumeration { public char nextElement(); public boolean hasMoreElements(); } AllUppercaseLettersInOrder implements ‘A’‘B’...‘Z’

Enumerating all Uppercase Letters public boolean hasMoreElements() { ???? } public char nextElement() { ??? } //instance variables ???

Enumerating all Uppercase Letters package enumerations; public class AllUpperCaseLettersInOrder implements CharEnumeration { char nextLetter = 'A'; public boolean hasMoreElements() { return nextLetter <= 'Z'; } public char nextElement() { char retVal = nextLetter; nextLetter = (char) (nextLetter + 1); return retVal; }

Comparing Two Implementations public interface CharEnumeration { public char nextElement(); public boolean hasMoreElements(); } JohnF.Kenndye token 1token 2token 3 AnUpperCaseEnumeration implements ‘J’‘F’‘K’

Radically Different Behaviors public interface CharEnumeration { public char nextElement(); public boolean hasMoreElements(); } AllUppercaseLettersInOrder implements ‘A’‘B’...‘Z’ print (new AnUppercaseEnumeration(s)); print (new AllUppercaseLettersInOrder()); Polymorphism Syntactic Specification!

Forward and reverse printing package main; import enums.CharEnumeration; import enums.AnUpperCaseEnumeration; public class AReverseUpperCasePrinter { static final int MAX_CHARS = 5; static char[] upperCaseLetters = new char[MAX_CHARS]; static int numberOfUpperCaseLetters = 0; public static void main(String[] args){ if (args.length != 1) { System.out.println("Illegal number of arguments:" + args.length + ". Terminating program."); System.exit(-1); } printAndStore(args[0]); printReverse(); }

Forward and reverse printing public static void printAndStore (String s) { System.out.println("Upper Case Letters:"); printAndStore (new AnUpperCaseEnumeration(s)); } public static void printAndStore (CharEnumeration charEnumeration) { while (charEnumeration.hasMoreElements()) { char inputChar = charEnumeration.nextElement(); System.out.print (inputChar); storeChar(inputChar); } System.out.println(); }

Forward and reverse printing (contd.) public static void storeChar(char c) { if (numberOfUpperCaseLetters == MAX_CHARS) { System.out.println("Too many upper case letters. Terminating program. "); System.exit(-1); } upperCaseLetters[numberOfUpperCaseLetters] = c; numberOfUpperCaseLetters++; } public static void printReverse() { System.out.println("Upper Case Letters in Reverse:"); for (int index =numberOfUpperCaseLetters - 1; index >= 0; index--) { System.out.print(upperCaseLetters[index]); }

Remaining problems package main; import enums.CharEnumeration; import enums.AnUpperCaseEnumeration; public class AReverseUpperCasePrinter { static final int MAX_CHARS = 5; static char[] upperCaseLetters = new char[MAX_CHARS]; static int numberOfUpperCaseLetters = 0; public static void main(String[] args){ if (args.length != 1) { System.out.println("Illegal number of arguments:" + args.length + ". Terminating program."); System.exit(-1); } printAndStore(args[0]); printReverse(); }

Remaining Problems Main class does storing Non UI code Array, size, and max size closely coupled to each other Should be in separate class

3 J F K sizearray Variable-Size Collection filled part unfilled part current size maximum size

Variable-Size Collection public class { … final static T A_MAX_SIZE = 50; T[] a = new T [MAX_SIZE]; int aSize = 0; … //process a for (int index = 0; index < aSize; index++) System.out.println(a[index]); … final int B_MAX_SIZE = 50; T[] b = new T [MAX_SIZE]; int bSize = 0; //process b … }

Special Type public class {... AVariableSizeTCollection a, b = new AVariableSizeTCollection();... for (int index = 0; index < a.size; index++) System.out.println(a.contents[index]); … AVariableSizeTCollection b = new AVariableSizeTCollection();... } public class AVariableSizeTCollection { public static final int MAX_SIZE = ???; public T[] contents = new T [MAX_SIZE]; public int size = 0; } No encapsulation! a.size = 0; Constraints violated

Supporting Encapsulation package collections; public interface …. { public static final int MAX_SIZE = 50; } public void addElement (char element); public void printReverse (); Implementation specific User specific

Supporting Encapsulation package collections; public interface CharHistory { } public void addElement (char element); public int size(); public char elementAt (int index);

Implementing the History package collections; public class ACharHistory implements CharHistory { public final int MAX_SIZE = 5; char[] contents = new char[MAX_SIZE]; int size = 0; public int size() { return size;} public char elementAt (int index) { return contents[index]; } boolean isFull() { return size == MAX_SIZE; } public void addElement(char element) { if (isFull()) { System.out.println("Adding item to a full history. Terminating program."); System.exit(-1); } else { contents[size] = element; size++; }

Using the History package main; import enums.CharEnumeration; import enums.AnUpperCaseEnumeration; import collections.ACharHistory; import collections.CharHistory; public class AModularReverseUpperCasePrinter { static CharHistory upperCaseLetters = new ACharHistory(); public static void main(String[] args) { if (args.length != 1) { System.out.println("Illegal number of arguments:" + args.length + ". Terminating program."); System.exit(-1); } printAndStore(args[0]); printReverse(); }

Using the History public static void printAndStore (String s) { System.out.println("Upper Case Letters:"); printAndStore (new AnUpperCaseEnumeration(s)); } public static void printAndStore (CharEnumeration charEnumeration) { while (charEnumeration.hasMoreElements()) { char inputChar = charEnumeration.nextElement(); System.out.print (inputChar); upperCaseLetters.addElement(inputChar); } System.out.println(); }

Forward and reverse printing (contd.) public static void printReverse() { System.out.println("Upper Case Letters in Reverse:"); for (int index =upperCaseLetters.size() - 1; index >= 0; index--) { System.out.print(upperCaseLetters.elementAt(index)); }