1 / 184

Intro to Computer Science I

Intro to Computer Science I. Chapter 4 Classes, Objects, and Methods OOP Concepts. Strings (1). A String is a sequence of 0 or more characters Every string has a length associated with it An empty string has length 0

muriel
Télécharger la présentation

Intro to Computer Science I

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Intro to Computer Science I Chapter 4 Classes, Objects, and Methods OOP Concepts

  2. Strings (1) • A String is a sequence of 0 or more characters • Every string has a length associated with it • An empty string has length 0 • Each character is stored internally as a 16-bit Unicode character (16-bit integer) • Each character in a string has an index associated with it.

  3. H e l l o 0 1 2 4 3 Strings (2) • Literal string: sequence of 0 or more characters delimited by double quote characters • Example: "Hello" • Empty string: "" • Memory model: The double quotes are not part of the string index begins at 0

  4. H e l l o 0 1 2 4 3 Substring • A substring is constructed by specifying a subsequence of characters A substring is a string e l l 0 1 2

  5. String Hello World Constructing a literal string • Strings are objects • String greeting = "Hello World"; greeting object referencevariable object reference object

  6. String expressions • Strings can be concatenated together • Numeric values can be automatically converted to strings • The + sign is used to denote addition and also string concatenation • RULE: In a + b if one of a or b is a string then the other will be converted to a string if necessary

  7. String expression examples String first = "William"; String middle = "James"; String last = "Duncan"; String fullName = first + " " + middle + " " + last; fullname has the value "William James Duncan"

  8. Mixed string expressions (1) String area = "Area: " + Math.sqrt(2.0); The value of area is"Area: 1.4142135623730951" You can try this in BeanShell and use print(area); to see the result

  9. Mixed string expressions (2) "The sum of " + x + " and " + y + " is " + x + y if x is 3 and y is 4 then the result of this expression is "The sum of 3 and 4 is 34" What's wrong?

  10. Length of a string • Prototype: • int length() • Example: String name = "Harry"; int len = name.length(); The value of len will be 5

  11. Number to string conversion • Examples String s1 = "" + age; String s2 = "" + area; If age is 34 and area is 2.34 then s1 and s2 will have the values "34" and "2.34"

  12. Extracting characters • Prototype: • char charAt(int index) • Example String s = "Hello"; char c = s.charAt(1); Here the value of c is 'e' (index begins at 0)

  13. Substring construction • Prototypes • String substring(int firstIndex) • String substring(int firstIndex, int lastIndexPlusOne) int d = 531452; String sd = "" + d; int len = sd.length(); sd = "$" + sd.substring(0,len-3) + "," + sd.substring(len-3); result is"$531,452"

  14. Trimming spaces • Prototype • String trim() String s = " Hello "; s = s.trim(); result is"Hello"

  15. String case conversion • upper/lower case conversion • Prototypes • String toLowerCase() • String toUpperCase() String test = "Hello"; String upper = test.toUpperCase(); String lower = test.toLowerCase(); char first = test.toLowerCase().charAt(0); results are "HELLO", "hello" and "h"

  16. String search methods • Searching for one string inside another • Prototypes • int indexOf(char ch) • int indexOf(char ch, int startIndex) • int indexOf(String sub) • int indexOf(String sub, int startIndex) signature Method Overloading: these methods all have the same name but they have different signatures

  17. String search examples String target = "This is the target string"; value is -1 target.indexOf('u') value is 8 target.indexOf("the") value is -1 target.indexOf("target",13)

  18. Displaying numbers, strings • Some prototypes: • void print(int n) • void print(double d) • void print(String s) • void println(int n) • void println(double d) • void println(String s) • void println() print but don't move to next line print and move to next line Output appears in the terminal window

  19. Examples: double area = 3.14159; System.out.println("Area: " + area); double area = 3.14159; System.out.print("Area: "); System.out.println(area); These produce the same results

  20. Examples: System.out.println("Hello"); System.out.print("Hello\n"); \ is called the escape character These produce the same results since \n is interpreted as the newline character

  21. Examples: System.out.println("\"\\Hello\\\""); Displayed result is "\Hello\"

  22. The BlueJ terminal window put this method in CircleCalculator class public void display(){ System.out.println("Radius = " + radius); System.out.println("Area = " + area); System.out.println("..."); }

  23. The toString method • Prototype • public String toString() • Purpose • return a string representation of an object • Default representation • toString is special: every class has a default toString method with a string representation that is not very useful so we normally provide our own version of this method.

  24. Default toString example bsh % addClassPath("c:/book-projects/chapter3"); bsh % CircleCalculator circle = new CircleCalculator(3.0); bsh % String rep = "toString gives " + circle; bsh % print(rep); toString gives CircleCalculator@4d1d41 bsh % rep = "toString gives " + circle.toString(); bsh % print(rep); toString gives CircleCalculator@4d1d41 bsh % print(circle); CircleCalculator@4d1d41 Not very meaningful Using the object name circle in a string expression is equvalent to using circle.toString()

  25. Define our own toString public String toString() { return "CircleCalculator[radius=" + radius + ", area=" + area + ", circumference=" + "]"; } now the displayed result is meaningful add this method to CircleCalculator cass print(circle); CircleCalculator[radius=3.0, area=28.274333882308138, circumference=18.84955592153876]

  26. Why toString ? • It is useful to write a toString method for every class. The toString representation of an object obj can be displayed using • System.out.println(obj); • This is useful for debugging classes (finding logical errors) since it provides an easy way to display the state of any object.

  27. Formatting data (Java 5) The String class contains a static method with prototype public static String format(String f, Object... args) Here f is the format string and Object... args represents the argument list of values to be formatted. There is also a new printf method that can be used with a format string that has the prototype public void printf(String f, Object... args)

  28. Format codes (Java 5) Format codes begin with % Here are some useful ones (see javadoc for complete list) %5d format an integer right justified in field of width 5 %-5d format at integer left justified in a field of width 5 %-20s format s string left justified in a field of width 20 %15.5f format a floating point number right justified in a field of width 15 using fixed format rounded to 5 digits after the decimal point %.5f format a floating point nuber in a field that just fits using fixed format rounded to 5 digits after the decimal point %20.8e format a floating point number right justified in a field of width 20 using exponential (scientific) format rounded to 8 digits after the decimal point

  29. Format example (1) The statements int i = 3; double pi = Math.PI; String end = "End"; String f = String.format("answer: %5d%15.5f%10s\n", i, pi, end); System.out.println(f); produce the output answer: 3 3.14159 End %5d %15.5f %10s

  30. Format example (2) The statements int i = 3; double pi = Math.PI; String end = "End"; System.out.printf("answer: %5d%15.5f%10s\n", I, pi, end); produce the same output using printf answer: 3 3.14159 End %5d %15.5f %10s To reuse formats use the format method in the String class

  31. Format example(3) In the CircleCalculator class we could include the following display method that formats the results. public void display() { System.out.printf("Radius = %.5f\n", radius); System.out.printf("Area = %.5f\n", area); System.out.printf("Circumference = %.5f\n", circumference); } to display the values rounded to 5 digits after the decimal point in fields that just fit.

  32. Intro to Computer Science I Chapter 4 Example classes that use the String class

  33. Design, Implement, Test • Begin with an English description of a class • Design the class by deciding what constructors and methods it should have. • This is called writing the public specification or public interface. • Write the complete class by providing the implementation • Test the class by itself using BlueJ

  34. BankAccount class description • A BankAccount object should represent a bank account using an account number, an owner name, and a current balance. • There should be a constructor for creating a bank account given these values. • There should be methods to withdraw or deposit a given amount and the usual "get methods" for retrurning the account number, owner name, and balance.

  35. BankAccount class design public class BankAccount { // instance data fields go here public BankAccount(int accountNumber, String ownerName, double initialBalance) {...} public void deposit(double amount) {...} public void withdraw(double amount) {...} public int getNumber() {...} public String getOwner() {...} public double getBalance() {...} public String toString() {...} }

  36. How will we use the class Construct an object BankAccount account = new BankAccount(123, "Fred", 125.50); withdraw $100 account.withdraw(100); display balance System.out.println("Balance is " + account.getBalance());

  37. formal and actual arguments Actual arguments in constructor call expression BankAccount myAccount = new BankAccount(123, "Fred", 125.50); Formal arguments in constructor prototype public BankAccount(int accountNumber, String ownerName, double initialBalance) { ... } Same idea applies to method call expressions and prototypes

  38. Implementing the class (1) • instance data fields private int number; private String name; private double balance;

  39. Implementing the class (2) • constructor implementation public BankAccount(int accountNumber, String ownerName, double initialBalance) { number = accountNumber; name = ownerName; balance = initialBalance; }

  40. Implementing the class (3) • deposit, withdraw (mutator methods) public void deposit(double amount) { balance = balance + amount; } public void withdraw(double amount) { balance = balance - amount; }

  41. Implementing the class (4) • get methods (enquiry methods) public int getNumber() { return number; } public String getName() { return name; } public double getBalance() { return balance; }

  42. Implementing the class (5) • toString method public String toString() { return "BankAccount[" + "number=" + number + ", name=" + name + ", balance=" + balance + "]"; }

  43. BankAccount class (1) public class BankAccount { private int number; private String name; private double balance; public BankAccount(int accountNumber, String ownerName, double initialBalance) { number = accountNumber; name = ownerName; balance = initialBalance; }

  44. BankAccount class (2) public void deposit(double amount) { balance = balance + amount; } public void withdraw(double amount) { balance = balance – amount; } public int getNumber() { return number; }

  45. BankAccount class (3) public String getName() { return name; } public double getBalance() { return balance; } public String toString() { return "BankAccount[number=" + number + ", name=" + name + ", balance=" + balance + "]"; } }

  46. BankAccount with BeanShell addClassPath("c:/book-projects/chapter4/bank-account"); BankAccount account = new BankAccount(123, "Fred", 125.50); account.withdraw(100); print(account.getBalance()); 25.5 account.deposit(100); print(account.getBalance()); 125.5 print(account); BankAccount[number=123, name=Fred, balance=125.5]

  47. BankAccount with BlueJ

  48. InitialsMaker description • An InitialsMaker object uses the first and last name of a person to produce the initials in uppercase. For example, if the name is Henry James or henry james then the initials are HJ.

  49. InitialsMaker design public class InitialsMaker { // instance data fields go here public InitialsMaker(String firstName, String lastName) {...} public String getInitials() {...} public String toString() {...} }

  50. Implementing the class (1) • instance data field • Another possibility private String initials; private String firstName; private String lastName; private String initials;

More Related