1 CSC 221: Computer Programming I Spring 2010 Design & text processing  design principles  cohesion & coupling  objects vs. primitives  String methods:

Slides:



Advertisements
Similar presentations
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Advertisements

Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
Java Programming Strings Chapter 7.
1 CSC 221: Computer Programming I Fall 2004 String manipulation  Java Strings: declaration, assignment, printing, concatenation  String traversal, construction,
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Programming 2 CS112- Lab 2 Java
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
Fundamental Programming Structures in Java: Strings.
String StringBuffer. class StringExample { public static void main (String[] args) { String str1 = "Seize the day"; String str2 = new String(); String.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
1 CSC 221: Computer Programming I Fall 2005 Repetition and Text Processing  Java Strings: declaration, assignment, printing, concatenation  String traversal,
1 CSC 221: Introduction to Programming Fall 2011 Text processing  Python strings  indexing & slicing, len function  functions vs. methods  string methods:
1 CSC 222: Object-Oriented Programming Spring 2012 Simulations & library classes  HW3: RouletteWheel, RouletteGame, RouletteTester  javadoc  java.lang.
Recursion A method is recursive if it makes a call to itself. A method is recursive if it makes a call to itself. For example: For example: public void.
1 CSC 221: Computer Programming I Spring 2010 interaction & design  modular design: roulette game  constants, static fields  % operator, string equals.
1 CSC 221: Introduction to Programming Fall 2012 Text processing  Python strings  indexing & slicing, len function  functions vs. methods  string methods:
1 CSC 222: Object-Oriented Programming Spring 2012 Object-oriented design  example: word frequencies w/ parallel lists  exception handling  System.out.format.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University ©2011 Pearson Prentice Hall ISBN Chapter 15 JavaScript.
String Manipulation. Java String class  The String class represents character strings “Tammy Bailey”  All strings (arrays of characters) in Java programs.
1 CSC 221: Computer Programming I Spring 2008 Class design & strings  design principles  cohesion & coupling  class example: graphical DotRace  static.
Introduction to Java Java Translation Program Structure
1 Textual Data Many computer applications manipulate textual data word processors web browsers online dictionaries.
Chapter 3: Classes and Objects Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Java’s String Class.
1 CSC 221: Introduction to Programming Fall 2011 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
CSC 1051 M.A. Papalaskari, Villanova University Everyday objects: Strings and Wrappers CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari.
G51PR1 Introduction to Programming I University of Nottingham Unit 8 : Strings.
String Processing Word processing term papers, writing memoirs, sending messages, responding to surveys, placing online orders and registering products.
Strings Mr. Smith AP Computer Science A. What are Strings? Name some of the characteristics of strings: A string is a sequence of characters, such as.
CSC Programming I Lecture 9 September 11, 2002.
1 CSC 221: Computer Programming I Fall 2009 Class design & strings  design principles  cohesion & coupling  example: graphical DotRace  objects vs.
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.
1 CSC 221: Computer Programming I Fall 2005 Class design & strings  design principles  cohesion & coupling  class examples: Hurricane, TaxReturn  objects.
1 CSC 222: Computer Programming II Spring 2004  classes and objects  abstract data types, classes and objects  using existing classes, #include, member.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
17-Feb-16 String and StringBuilder Part I: String.
Strings, Characters, and Regular Expressions Session 10 Mata kuliah: M0874 – Programming II Tahun: 2010.
Chapter 8: Loops, Arrays, Strings Loop statements –do –while –for Arrays –declaration, allocation, initialization, access –multi-dimensional –heterogeneous.
CSC 221: Computer Programming I Fall 2001  C++ libraries  cmath, cctype  classes and objects  abstract data types, classes and objects  data fields,
1 CSC 221: Computer Programming I Fall 2005 graphics & design  Dot & DotRace revisited  Circle class implementation  adding Circle methods  static.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 15 JavaScript.
The Methods and What You Need to Know for the AP Exam
CSC 222: Object-Oriented Programming Fall 2017
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Strings, Characters and Regular Expressions
CSC 222: Object-Oriented Programming
CSC 222: Object-Oriented Programming Spring 2013
CSC 222: Object-Oriented Programming Spring 2015
CSC 222: Object-Oriented Programming Fall 2017
Primitive Types Vs. Reference Types, Strings, Enumerations
String Objects & its Methods
CS 106A, Lecture 9 Problem-Solving with Strings
Chapter 7: Strings and Characters
Can store many of the same kind of data together
CSC 221: Introduction to Programming Fall 2018
CSC 222: Object-Oriented Programming Spring 2012
CSC 222: Object-Oriented Programming Spring 2013
Introduction to Computer Science
String methods 26-Apr-19.
CSC 222: Object-Oriented Programming Spring 2012
In Java, strings are objects that belong to class java.lang.String .
Presentation transcript:

1 CSC 221: Computer Programming I Spring 2010 Design & text processing  design principles  cohesion & coupling  objects vs. primitives  String methods: length, charAt, substring, indexOf, …  StringUtils class/library  examples: Palindromes, Pig Latin

2 Object-oriented design principles so far:  a class should model some entity, encapsulating all of its state and behaviors e.g., Circle, Die, Dot, DotRace, …  a field should store a value that is part of the state of an object (and which must persist between method calls) e.g., xPosition, yPosition, color, diameter, isVisible, … can be primitive (e.g., int, double ) or object (e.g., String, Die ) type should be declared private to avoid outside tampering with the fields – provide public accessor methods if needed static fields should be used if the data can be shared among all objects final-static fields should be used to define constants with meaningful names  a constructor should initialize the fields when creating an object can have more than one constructor with different parameters to initialize differently  a method should implement one behavior of an object e.g., moveLeft, moveRight, draw, erase, changeColor, … should be declared public to make accessible – helper methods can be private local variables should be used to store temporary values that are needed if statements for conditional execution; while loops for conditional repetition; for loops for counter-driven repetition

3 Cohesion cohesion describes how well a unit of code maps to an entity or behavior in a highly cohesive system:  each class maps to a single, well-defined entity – encapsulating all of its internal state and external behaviors  each method of the class maps to a single, well-defined behavior advantages of cohesion:  highly cohesive code is easier to read don't have to keep track of all the things a method does if the method name is descriptive, it makes it easy to follow code  highly cohesive code is easier to reuse if the class cleanly models an entity, can reuse it in any application that needs it if a method cleanly implements a behavior, it can be called by other methods and even reused in other classes

4 Coupling coupling describes the interconnectedness of classes in a loosely coupled system:  each class is largely independent and communicates with other classes via small, well-defined interfaces advantages of loose coupling:  loosely coupled classes make changes simpler can modify the implementation of one class without affecting other classes only changes to the interface (e.g., adding/removing methods, changing the parameters) affect other classes  loosely coupled classes make development easier you don't have to know how a class works in order to use it since fields/local variables are encapsulated within a class/method, their names cannot conflict with the development of other classes.methods

5 Strings vs. primitives although they behave similarly to primitive types (int, double, char, boolean), Strings are different in nature  String is a class that is defined in a separate library: java.lang.String  a String value is really an object  you can call methods on a String  also, you can Inspect the String fields of an object

6 Comparing strings comparison operators ( >= ) are defined for primitives but not objects String str1 = "foo"; // EQUIVALENT TO String str1 = new String("foo"); String str2 = "bar"; // EQUIVALENT TO String str2 = new String("bar"); if (str1 < str2) … // ILLEGAL == and != are defined for objects, but don't do what you think if (str1 == str2) … // TESTS WHETHER THEY ARE THE // SAME OBJECT, NOT WHETHER THEY // HAVE THE SAME VALUE! Strings are comparable using the equals and compareTo methods if (str1.equals(str2)) … // true IF THEY REPRESENT THE // SAME STRING VALUE if (str1.compareTo(str2) < 0) … // RETURNS -1 if str1 < str2 // RETURNS 0 if str1 == str2 // RETURNS 1 if str1 > str2

7 On Test 1… we now know better, should use equals for the comparison if (response.equals("yes")) { this.numOfYes++; } else if (response.equals("no")) { this.numOfNo++; } for inequality, combine equals with ! if (!response.equals("maybe")) {... } code on Test 1 included the following if-else if (response == "yes") { this.numOfYes++; } else if (response == "no") { this.numOfNo++; } never use == for comparing Strings  sometimes it works, but not always

8 String methods in addition, there are many useful methods defined for Strings int length() returns the length of the String str char charAt(int index) returns the character at specified index first index is 0 last index is str.length()-1 if index = str.length(), an error occurs String str = "foobar"; for (int i = 0; i < str.length(); i++) { System.out.print(str.charAt(i)); } String str = "foobar"; for (int i = str.length()-1; i >= 0; i--) { System.out.print(str.charAt(i)); } String str = "foobar"; System.out.println( str.length() ); System.out.println( str.charAt(0) ); System.out.println( str.charAt(1) ); System.out.println( str.charAt(str.length()-1) );

9 Traversing & constructing Strings since the length of a String can be determined using the length method, a for loop can be used to traverse the String  as you access individual characters, can test and act upon values  can even construct a new string out of individual characters String str = "zaboomofoo"; int count = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == 'o') { count++; } String copy = ""; for (int i = 0; i < str.length(); i++) { copy = str.charAt(i) + copy; } String copy = ""; for (int i = 0; i < str.length(); i++) { copy = copy + str.charAt(i); }

10 String utilities we can define and encapsulate additional string operations in a class  StringUtils will not have any fields, it simply encapsulates methods  can define methods to be static – static methods can be called directly on the class (i.e., don't have to create a StringUtils onject, can call methods from the class icon) public class StringUtils { /** * Reverses a string. str the string to be reversed a copy of str with the order of the characters reversed */ public static String reverse(String str) { String copy = ""; for (int i = 0; i < str.length(); i++) { copy = str.charAt(i) + copy; } return copy; }. }

11 Stripping a string consider the task of removing non-letters from a string  need to traverse the string and check each char to see if it is a letter Character.isLetter is a predefined static method that does this  if the char is a letter, add that char to the copy string  if not, ignore the letter /** * Removes all non-letters from a string. str the string to be stripped a copy of str with all non-letters removed */ public static String stripNonLetters(String str) { String copy = ""; for (int i = 0; i < str.length(); i++) { char nextChar = str.charAt(i); if (Character.isLetter(nextChar)) { copy += nextChar; } return copy; }

12 Palindrome suppose we want to define a method to test whether a word or phrase is a palindrome (i.e., same forwards and backwards, ignoring non-letters) "bob" "madam" "Madam, I'm Adam." "Able was I ere I saw Elba." "A man, a plan, a canal: Panama." /** * Determines whether a string is a palindrome. str the string to be tested true if the string is a palindrome; else, false */ public static boolean isPalindrome(String str) { str = str.toLowerCase(); str = StringUtils.stripNonLetters(str); String reverseStr = StringUtils.reverse(str); return (str.equals(reverseStr)); }

13 Substring it is possible to extract part of a String: String substring(int start, int end) returns the substring starting at index start and ending at index end-1 e.g., String str = "foobar"; str.substring(0,3)  "foo" str.substring(3, str.length())  "bar" /** * Capitalizes the first letter in the string. str the string to be capitalized a copy of str with the first letter capitalized */ public static String capitalize(String str) { return Character.toUpperCase(str.charAt(0)) + str.substring(1, str.length()); }

14 Pig Latin suppose we want to translate a word into Pig Latin  simplest version pig  igpaylatin  atinlay shoe  oeshaychronic  onicchray apple  applewaynth  nthway  describe an algorithm that covers all cases /** * Translates a word into Pig Latin str the word to be translated (no spaces or punctuation) the translated word in Pig Latin */ public static String pigLatin(String str) { int firstVowel = StringUtils.findVowel(str); if (firstVowel <= 0) { return str + "way"; } else { return str.substring(firstVowel, str.length()) + str.substring(0,firstVowel) + "ay"; }

15 Implementing findVowel need to traverse the string, checking each character to see if it is a vowel  can avoid having to look for upper- and lower-case vowels by using toLowerCase /** * Finds the first occurrence of a vowel in a string. str the string to be searched the index of the first occurrence of a vowel from seq */ public static int findVowel(String str) { str = str.toLowerCase(); for (int i = 0; i < str.length(); i++) { char nextChar = str.charAt(i); if (nextChar == 'a' || nextChar == 'e' || nextChar == 'i' || nextChar == 'o' || nextChar == 'u') { return i; } return -1; }

16 Better solution using indexOf the indexOf method will search for a letter or substring in a String  returns index of first occurrence, or -1 if not found e.g., String str = "foobar"; str.indexOf('b')  3 str.indexOf("oo")  1 str.indexOf("fool")  -1 /** * Finds the first occurrence of a vowel in a string. str the string to be searched the index of the first occurrence of a vowel from seq */ public static int findVowel(String str) { str = str.toLowerCase(); String vowels = "aeiou"; for (int i = 0; i < str.length(); i++) { char nextChar = str.charAt(i); if (vowels.indexOf(nextChar) != -1) { return i; } return -1; }

17 Testing code when you design and write code, how do you know if it works?  run it a few times and assume it's OK? to be convinced that code runs correctly in all cases, you must analyze the code and identify special cases that are handled  then, define a test data set (inputs & corresponding outputs) that covers those cases  e.g., for Pig Latin, words that start with single consonant:"foo"  "oofay" "banana"  "ananabay" words that start with multiple consonants: "thrill"  "illthray" "cheese"  "eesechay" words that start with vowel: "apple"  "appleway" "oops"  "oopsway" words with no vowels: "nth"  "nthway" what about capitalization? punctuation? digits?

18 String method summary int length() returns number of chars in String char charAt(int index) returns the character at the specified index (indices range from 0 to str.length()-1) int indexOf(char ch) returns index where the specified char/substring int indexOf(String str) first occurs in the String (-1 if not found) String substring(int start, int end) returns the substring from indices start to (end-1) String toUpperCase() returns copy of String with all letters uppercase String toLowerCase() returns copy of String with all letters lowercase boolean equals(String other) returns true if other String has same value int compareTo(String other) returns -1 if less than other String, 0 if equal to other String, 1 if greater than other String ALSO, from the Character class: char Character.toLowerCase(char ch) returns lowercase copy of ch char Character.toUpperCase(char ch) returns uppercase copy of ch boolean Character.isLetter(char ch) returns true if ch is a letter boolean Character.isLowerCase(char ch) returns true if lowercase letter boolean Character.isUpperCase(char ch) returns true if uppercase letter