Using Objects (continued)

Slides:



Advertisements
Similar presentations
Copyright 2010 by Pearson Education Building Java Programs Chapter 4 Lecture 4-2: Advanced if/else ; Cumulative sum reading: 4.1, 4.3, 4.5; "Procedural.
Advertisements

Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner.
Copyright 2006 by Pearson Education 1 reading: 4.1 Cumulative sum.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 8: Classes and Objects.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 4 Lecture 4-3: Strings and objects; printf reading: 3.3, self-check: Ch.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapters 3-4: Using Objects.
Objects and Classes; Strings. 2 Classes and objects class: A program entity that represents either 1.A program / module, or 2.A type of objects* –A class.
Objects.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
1 Object state: fields. Fields field: A variable inside an object that represents part of its internal state.  Each object will have its own copy of.
1 Fencepost loops suggested reading: The fencepost problem Problem: Write a static method named printNumbers that prints each number from 1 to a.
1 BUILDING JAVA PROGRAMS CHAPTER 3 THE STRING CLASS.
CS305j Introduction to Computing Classes 1 Topic 23 Classes – Part I "A 'class' is where we teach an 'object' to behave." -Rich Pattis Based on slides.
Cumulative algorithms. 2 Adding many numbers How would you find the sum of all integers from ? // This may require a lot of typing int sum = 1 +
CHAPTER 6 GC Strings. THE CLASS STRING  Contains operations to manipulate strings.  String:  Sequence of zero or more characters.  Enclosed.
1 BUILDING JAVA PROGRAMS CHAPTER 5 PROGRAM LOGIC AND INDEFINITE LOOPS.
Building Java Programs Chapter 4 Lecture 4-1: Scanner ; cumulative algorithms reading: 3.3 – 3.4, 4.2.
Copyright 2010 by Pearson Education Building Java Programs Chapter 4 Lecture 4-3: Strings, char reading: 3.3, 4.3.
1 reading: 3.3 Using objects. Objects So far, we have seen: methods, which represent behavior variables, which represent data (categorized by types) It.
Building Java Programs
Building Java Programs
Building Java Programs
Lecture 8: The String class
Building Java Programs
CSCI 161 – Introduction to Programming I William Killian
Building Java Programs
Chapter 6 GC 101 Strings.
Conditional Execution
CSc 110, Autumn 2016 Lecture 12: Advanced if/else; Cumulative sum
Topic 9 Using Objects, Interactive Programs and Loop Techniques
Building Java Programs
Building Java Programs
CSc 110, Spring 2017 Lecture 9: Advanced if/else; Cumulative sum
Building Java Programs
Building Java Programs
Lecture 5: For Loops Building Java Programs: A Back to Basics Approach
Building Java Programs
Building Java Programs
Building Java Programs
CSE 142 Lecture Notes Defining New Types of Objects
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
CSE 142 Lecture Notes Defining New Types of Objects, cont'd.
Building Java Programs
Building Java Programs
Building Java Programs
Classes and objects Readings: 8.1.
Building Java Programs
Strings string: An object storing a sequence of text characters.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Presentation transcript:

Using Objects (continued) suggested reading: 3.3

String objects One of the most common types of objects in Java is type String. String: A sequence of text characters. String variables can be declared and assigned, just like primitive values: String <name> = "<text>"; String <name> = <expression that produces a String>; Unlike most other objects, Strings are not created with new. Examples: String name = "Marla Singer"; int x = 3, y = 5; String point = "(" + x + ", " + y + ")";

Indexes The characters in a String are each internally numbered with an index, starting with 0 for the first character: Example: String name = "M. Stepp"; Individual text characters are represented inside the String by a primitive type called char. Literal char values are surrounded with apostrophe (single-quote) marks, such as 'a' or '4'. An escape sequence can be represented as a char, such as '\n' (new-line character) or '\'' (apostrophe). index 1 2 3 4 5 6 7 character 'M' '.' ' ' 'S' 't' 'e' 'p'

String methods Here are several of the most useful String methods: Method name Description charAt(index) character at a specific index indexOf(String) index where the start of the given String appears in this String (-1 if it is not there) length() number of characters in this String substring(index1, index2) the characters from index1 to just before index2 toLowerCase() a new String with all lowercase letters toUpperCase() a new String with all uppercase letters

String method examples // index 012345678901 String s1 = "Stuart Reges"; String s2 = "Marty Stepp"; System.out.println(s1.length()); // 12 System.out.println(s1.indexOf("e")); // 8 System.out.println(s1.substring(1, 4)); // tua String s3 = s2.toUpperCase(); System.out.println(s3.substring(6, 10)); // STEP String s4 = s1.substring(0, 6); System.out.println(s4.toLowerCase()); // stuart

String methods Given the following String: String book = "Building Java Programs"; How would you extract the word "Java" ? How would you change book to store: "BUILDING JAVA PROGRAMS" ? How would you extract the first word from any general String? Method name Description charAt(index) character at a specific index indexOf(String) index where the start of the given String appears in this String (-1 if it is not there) length() number of characters in this String substring(index1, index2) the characters from index1 to just before index2 toLowerCase() a new String with all lowercase letters toUpperCase() a new String with all uppercase letters

Point objects Java has a type of objects named Point. To use Point, you must write: import java.awt.*; Constructing a Point object, general syntax: Point <name> = new Point(<x>, <y>); Point <name> = new Point(); // the origin, (0, 0) Example: Point p1 = new Point(5, -2); Point p2 = new Point(); // 0, 0 Point objects are useful for several reasons: In programs that do a lot of 2D graphics, it can be nice to be able to store an (x, y) pair in a single variable. Points have several useful geometric methods we can call in our programs.

Point object methods Data stored in each Point object: Useful methods of each Point object: Point objects can also be output to the console using println statements. Field name Description x Point's x-coordinate y Point's y-coordinate Method name Description distance(Point) how far apart these two Points are setLocation(x, y) changes this Point's x and y to be the given values translate(dx, dy) adjusts this Point's x and y by the given difference amounts

Using Point objects An example program that uses Point objects: import java.awt.*; public class PointMain { public static void main(String[] args) { // create two Point objects Point p1 = new Point(7, 2); Point p2 = new Point(4, 3); // print each point and their distance apart System.out.println("p1 is " + p1); System.out.println("p2: (" + p2.x + ", " + p2.y + ")"); System.out.println("distance = " + p1.distance(p2)); // translate the point to a new location p2.translate(1, 7); System.out.println("p2 is " + p2); }

Point objects question Write a program that plays a point guessing game. When the user is wrong, the program hints which way to go. Define (4, 2) as the correct answer for every game, for now. I'm thinking of a point somewhere between (1, 1) and (5, 5) ... It is 4.47213595499958 from the origin. guess x and y? 1 1 right up guess x and y? 5 1 left up guess x and y? 3 4 right down guess x and y? 4 3 down guess x and y? 4 2 you guessed it!

Cumulative sum suggested reading: 4.1

Adding many numbers Consider the following code to read three values from the user and add them together: Scanner console = new Scanner(System.in); System.out.print("Type a number: "); int num1 = console.nextInt(); int num2 = console.nextInt(); int num3 = console.nextInt(); int sum = num1 + num2 + num3; System.out.println("The sum is " + sum);

A cumulative sum You may have observed that the variables num1, num2, and num3 are unnecessary. The code can be improved: Scanner console = new Scanner(System.in); System.out.print("Type a number: "); int sum = console.nextInt(); sum += console.nextInt(); System.out.println("The sum is " + sum); cumulative sum: A sum variable that keeps a total-in-progress and is updated many times until the task of summing is finished. The variable sum in the above code now represents a cumulative sum.

Failed cumulative sum loop How would we modify the preceding code to sum 100 numbers? Creating 100 copies of the same code would be redundant. A failed attempt to write a loop to add 100 numbers: The scope of sum is inside the for loop, so the last line of code fails to compile. Scanner console = new Scanner(System.in); for (int i = 1; i <= 100; i++) { int sum = 0; System.out.print("Type a number: "); sum += console.nextInt(); } // sum is undefined here System.out.println("The sum is " + sum);

Fixed cumulative sum loop A corrected version of the sum loop code: Scanner console = new Scanner(System.in); int sum = 0; for (int i = 1; i <= 100; i++) { System.out.print("Type a number: "); sum += console.nextInt(); } System.out.println("The sum is " + sum); The key idea: Cumulative sum variables must always be declared outside the loops that update them, so that they will continue to live after the loop is finished.

User-guided cumulative sum The user's input can guide the number of times the cumulative loop repeats: Scanner console = new Scanner(System.in); System.out.print("How many numbers to add? "); int count = console.nextInt(); int sum = 0; for (int i = 1; i <= count; i++) { System.out.print("Type a number: "); sum += console.nextInt(); } System.out.println("The sum is " + sum); An example output: How many numbers to add? 3 Type a number: 2 Type a number: 6 Type a number: 3 The sum is 11

Variation: cumulative product The same idea can be used with other operators, such as multiplication which produces a cumulative product: Scanner console = new Scanner(System.in); System.out.print("Raise 2 to what power? "); int exponent = console.nextInt(); int product = 1; for (int i = 1; i <= exponent; i++) { product = product * 2; } System.out.println("2 to the " + exponent + " = " + product); Exercise: Change the above code so that it also prompts for the base, instead of always using 2. Exercise: Make the code to compute the powers into a method which accepts a base a and exponent b as parameters and returns ab .

Cumulative sum question Write a program that reads input of the number of hours two employees have worked and displays each employee's total and the overall total hours. The company doesn't pay overtime, so cap any day at 8 hours. Example log of execution: Employee 1: How many days? 3 Hours? 6 Hours? 12 Hours? 5 Employee 1's total paid hours = 19 Employee 2: How many days? 2 Hours? 11 Employee 2's total hours = 14 Total paid hours for both employees = 33