"; String Download presentation Presentation is loading. Please wait.
1
Using Objects (continued)
2
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 + ")";
3
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'
4
String methods Here are several of the most useful String methods:
5
String method examples
6
String methods Given the following String:
7
Point objects Java has a type of objects named Point.
8
Point object methods Data stored in each Point object:
9
Using Point objects An example program that uses Point objects:
10
Point objects question
11
Cumulative sum suggested reading: 4.1
12
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);
13
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.
14
Failed cumulative sum loop
15
Fixed cumulative sum loop
16
User-guided cumulative sum
17
Variation: cumulative product
18
Cumulative sum question
Similar presentations © 2024 SlidePlayer.com. Inc. Log in
Similar presentations
Presentation on theme: "Using Objects (continued)"— Presentation transcript:
suggested reading: 3.3
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
// index 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 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
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.
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
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); }
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 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!
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);
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.
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
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 .
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
Similar presentations
All rights reserved.