Transcript ch03-3
Using Objects (continued)
suggested reading: 3.3
1
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 + ")";
2
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";
index
0
character 'M'
1
2
3
4
5
6
7
'.'
' '
'S'
't'
'e'
'p'
'p'
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).
3
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
4
String method examples
//
index 012345678901
String s1 = "Stuart Reges";
String s2 = "Marty Stepp";
System.out.println(s1.length());
System.out.println(s1.indexOf("e"));
System.out.println(s1.substring(1, 4));
// 12
// 8
// 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
5
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
6
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.
7
Point object methods
Data stored in each Point object:
Field name
x
Point's x-coordinate
y
Point's y-coordinate
Useful methods of each Point object:
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
adjusts this Point's x and y by the given
difference amounts
translate(dx, dy)
Description
Point objects can also be output to the console using
println statements.
8
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);
System.out.println("distance = " + p1.distance(p2));
}
}
9
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
right up
guess x and
left up
guess x and
right down
guess x and
down
guess x and
you guessed
y? 1 1
y? 5 1
y? 3 4
y? 4 3
y? 4 2
it!
10
Cumulative sum
suggested reading: 4.1
11
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();
System.out.print("Type a number: ");
int num2 = console.nextInt();
System.out.print("Type a number: ");
int num3 = console.nextInt();
int sum = num1 + num2 + num3;
System.out.println("The sum is " + sum);
12
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();
System.out.print("Type a number: ");
sum += console.nextInt();
System.out.print("Type a number: ");
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.
13
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);
14
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.
15
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
16
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 .
17
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
Hours? 6
Employee 2's total hours = 14
Total paid hours for both employees = 33
18