Vous êtes sur la page 1sur 191

Objects and Classes

Each part a home builder


uses, such as a furnace or
a water heater, fulfills a
particular function.
Similarly, you build
programs from objects,
each of which has a
particular behavior.

In Java, you build programs for objects.


Each object has certain behaviors.
You can manipulate the object to get certain effects.

Character Strings
A string literal is represented by putting double
quotes around the text
Examples:
"This is a string literal."
"123 Main Street"
"X"

Every character string is an object in Java, defined


by the String class
Every string literal represents a String object

Copyright 2012 Pearson Education, Inc.

The println Method


In the Lincoln program from Chapter 1, we
invoked the println method to print a character
string
The System.out object represents a destination
(the monitor screen) to which we can send output
System.out.println ("Whatever you are, be a good one.");

object

method
information provided to the method
name
(parameters)

Copyright 2012 Pearson Education, Inc.

The print Method


The System.out object provides another service
as well
The print method is similar to the println
method, except that it does not advance to the
next line
Therefore anything printed after a print
statement will appear on the same line
See Countdown.java

Copyright 2012 Pearson Education, Inc.

//********************************************************************
// Countdown.java
Author: Lewis/Loftus
//
// Demonstrates the difference between print and println.
//********************************************************************
public class Countdown
{
//----------------------------------------------------------------// Prints two lines of output representing a rocket countdown.
//----------------------------------------------------------------public static void main (String[] args)
{
System.out.print ("Three... ");
System.out.print ("Two... ");
System.out.print ("One... ");
System.out.print ("Zero... ");
System.out.println ("Liftoff!"); // appears on first output line
System.out.println ("Houston, we have a problem.");
}
}

Copyright 2012 Pearson Education, Inc.

Output

//********************************************************************
// Countdown.java
Author: Lewis/Loftus
Three...
Two...
One... Zero... Liftoff!
//
// Demonstrates
the we
difference
print and println.
Houston,
have between
a problem.
//********************************************************************
public class Countdown
{
//----------------------------------------------------------------// Prints two lines of output representing a rocket countdown.
//----------------------------------------------------------------public static void main (String[] args)
{
System.out.print ("Three... ");
System.out.print ("Two... ");
System.out.print ("One... ");
System.out.print ("Zero... ");
System.out.println ("Liftoff!"); // appears on first output line
System.out.println ("Houston, we have a problem.");
}
}

Copyright 2012 Pearson Education, Inc.

String Concatenation
The string concatenation operator (+) is used to
append one string to the end of another
"Peanut butter " + "and jelly"
It can also be used to append a number to a string
A string literal cannot be broken across two lines in
a program
See Facts.java

Copyright 2012 Pearson Education, Inc.

//********************************************************************
// Facts.java
Author: Lewis/Loftus
//
// Demonstrates the use of the string concatenation operator and the
// automatic conversion of an integer to a string.
//********************************************************************
public class Facts
{
//----------------------------------------------------------------// Prints various facts.
//----------------------------------------------------------------public static void main (String[] args)
{
// Strings can be concatenated into one long string
System.out.println ("We present the following facts for your "
+ "extracurricular edification:");
System.out.println ();
// A string can contain numeric digits
System.out.println ("Letters in the Hawaiian alphabet: 12");
continue

Copyright 2012 Pearson Education, Inc.

continue
// A numeric value can be concatenated to a string
System.out.println ("Dialing code for Antarctica: " + 672);
System.out.println ("Year in which Leonardo da Vinci invented "
+ "the parachute: " + 1515);
System.out.println ("Speed of ketchup: " + 40 + " km per year");
}
}

Copyright 2012 Pearson Education, Inc.

Output
continue
We present the following facts for your extracurricular edification:
// A numeric value can be concatenated to a string
Letters
in the Hawaiian ("Dialing
alphabet: code
12
System.out.println
for Antarctica: " + 672);
Dialing code for Antarctica: 672
Year System.out.println
in which Leonardo da
Vinciininvented
the parachute:
("Year
which Leonardo
da Vinci1515
invented "
Speed of ketchup: 40 km per
year
+ "the parachute: " + 1515);
System.out.println ("Speed of ketchup: " + 40 + " km per year");
}
}

Copyright 2012 Pearson Education, Inc.

String Concatenation
The + operator is also used for arithmetic addition
The function that it performs depends on the type of the
information on which it operates
If both operands are strings, or if one is a string and one is
a number, it performs string concatenation
If both operands are numeric, it adds them
The + operator is evaluated left to right, but parentheses
can be used to force the order
See Addition.java

Copyright 2012 Pearson Education, Inc.

//********************************************************************
// Addition.java
Author: Lewis/Loftus
//
// Demonstrates the difference between the addition and string
// concatenation operators.
//********************************************************************
public class Addition
{
//----------------------------------------------------------------// Concatenates and adds two numbers and prints the results.
//----------------------------------------------------------------public static void main (String[] args)
{
System.out.println ("24 and 45 concatenated: " + 24 + 45);
System.out.println ("24 and 45 added: " + (24 + 45));
}
}

Copyright 2012 Pearson Education, Inc.

Output

//********************************************************************
// Addition.java
Author: Lewis/Loftus
24
and
45 concatenated: 2445
//
// Demonstrates
difference
between69
the addition and string
24the
and
45 added:
// concatenation operators.
//********************************************************************
public class Addition
{
//----------------------------------------------------------------// Concatenates and adds two numbers and prints the results.
//----------------------------------------------------------------public static void main (String[] args)
{
System.out.println ("24 and 45 concatenated: " + 24 + 45);
System.out.println ("24 and 45 added: " + (24 + 45));
}
}

Copyright 2012 Pearson Education, Inc.

Quick Check
What output is produced by the following?
System.out.println ("X: " + 25);
System.out.println ("Y: " + (15 + 50));
System.out.println ("Z: " + 300 + 50);

Copyright 2012 Pearson Education, Inc.

Quick Check
What output is produced by the following?
System.out.println ("X: " + 25);
System.out.println ("Y: " + (15 + 50));
System.out.println ("Z: " + 300 + 50);
X: 25
Y: 65
Z: 30050

Copyright 2012 Pearson Education, Inc.

Escape Sequences
What if we wanted to print the quote character?
The following line would confuse the compiler because it
would interpret the second quote as the end of the string
System.out.println ("I said "Hello" to you.");

An escape sequence is a series of characters that


represents a special character
An escape sequence begins with a backslash character (\)
System.out.println ("I said \"Hello\" to you.");

Copyright 2012 Pearson Education, Inc.

Escape Sequences
Some Java escape sequences:
Escape Sequence Meaning
backspace
tab
newline
carriage return
double quote
single quote
backslash

\b
\t
\n
\r
\"
\'
\\

See Roses.java

Copyright 2012 Pearson Education, Inc.

//********************************************************************
// Roses.java
Author: Lewis/Loftus
//
// Demonstrates the use of escape sequences.
//********************************************************************
public class Roses
{
//----------------------------------------------------------------// Prints a poem (of sorts) on multiple lines.
//----------------------------------------------------------------public static void main (String[] args)
{
System.out.println ("Roses are red,\n\tViolets are blue,\n" +
"Sugar is sweet,\n\tBut I have \"commitment issues\",\n\t" +
"So I'd rather just be friends\n\tAt this point in our " +
"relationship.");
}
}

Copyright 2012 Pearson Education, Inc.

Output
//********************************************************************
// Roses.java
Author:
Lewis/Loftus
Roses are
red,
//
Violets are blue,
// Demonstrates the use of escape sequences.
Sugar is sweet,
//********************************************************************

But I have "commitment issues",

public class Roses


So I'd rather just be friends
{
//----------------------------------------------------------------At this point in our relationship.
// Prints a poem (of sorts) on multiple lines.
//----------------------------------------------------------------public static void main (String[] args)
{
System.out.println ("Roses are red,\n\tViolets are blue,\n" +
"Sugar is sweet,\n\tBut I have \"commitment issues\",\n\t" +
"So I'd rather just be friends\n\tAt this point in our " +
"relationship.");
}
}

Copyright 2012 Pearson Education, Inc.

Quick Check
Write a single println statement that produces the
following output:
"Thank you all for coming to my home
tonight," he said mysteriously.

Copyright 2012 Pearson Education, Inc.

Quick Check
Write a single println statement that produces the
following output:
"Thank you all for coming to my home
tonight," he said mysteriously.

System.out.println ("\"Thank you all for " +


"coming to my home\ntonight,\" he said " +
"mysteriously.");

Copyright 2012 Pearson Education, Inc.

Using Objects
Object: an entity in your program that you can
manipulate by calling one or more of its methods.
Method: consists of a sequence of instructions that
can access the data of an object.
You do not know what the instructions are
You do know that the behavior is well defined

System .out has a println method


You do not know how it works
What is important is that it does the work you request of it

Using Objects

Figure 1 Representation of the System .out Object

Using Objects
You can think of a water heater as
an object that can carry out the "get
hot water" method. When you call
that method to enjoy a hot shower,
you don't care whether the water
heater uses gas or solar power.

Classes
A class describes a set of objects with the same behavior.
Some string objects:
"H ello W orld"
"G oodbye"
"M ississippi"

You can invoke the same methods on all strings.


System .out is a member of the PrintStream class that
writes to the console window.
You can construct other objects of PrintStream class
that write to different destinations.
All PrintStream objects have methods println and
print.

Classes
Objects of the PrintStream class have a completely
different behavior than the objects of the String class.
Different classes have different responsibilities
A string knows about the letters that it contains
A string doesn't know how to send itself to a console window or file.

All objects of the W indow class share the same


behavior.

Self Check 2.1


In Java, objects are grouped into classes according to their
behavior. Would a window object and a water heater object
belong to the same class or to different classes? Why?

Answer: Objects with the same behavior belong to


the same class. A window lets in light while
protecting a room from the outside wind and
heat or cold. A water heater has completely
different behavior. It heats water. They belong to
different classes.

Self Check 2.2


Some light bulbs use a glowing filament, others use a
fluorescent gas. If you consider a light bulb a Java object with
an "illuminate" method, would you need to know which kind of
bulb it is?

Answer: When one calls a method, one is not


concerned with how it does its job. As long as a
light bulb illuminates a room, it doesn't matter to
the occupant how the photons are produced.

Variables
Use a variable to store a value that you want to use later
To declare a variable named w idth:
int w idth = 20;

Like a variable in a computer program, a parking


space has an identifier and a contents.

Syntax 2.1 Variable Declaration

Variables
A variable is a storage location
Has a name and holds a value

When declaring a variable, you usually specify an initial value.


When declaring a variable, you also specify the type of its
values.
Variable declaration: int w idth = 20:
w idth is the name
int is the type
20 is the initial value

Variables
Each parking space is suitable for a particular type of
vehicle, just as each variable holds a value of a
particular type.

Variable Declarations

Types
Use the int type for numbers that cannot have a
fractional part.
int w idth = 20;

Use the double type for floating point numbers.


double m ilesPerG allon = 22.5;

Numbers can be combined by arithmetic operators


such as + , -, and *
Another type is String
String greeting = "H ello";

A type specifies the operations that can be carried


out with its values.
You can multiply the value width holds by a number
You can not multiply greetings by a number.

Names
Pick a name for a variable that describes its purpose.
Rules for the names of variables, methods, and classes:
Must start with a letter or the underscore (_) character, and the remaining
characters must be letters, numbers, or underscores.
Cannot use other symbols such as ? or % or a space
Use uppercase letters to denote word boundaries, as in m ilesPerG allon.
(Called camel case)

Names are case sensitive


You cannot use reserved words such as double or class

Names
By Java convention:
variable names start with a lowercase letter.
class names start with an uppercase letter.

Variable Names in Java

Comments
Use comments to add explanations for humans who
read your code.
double m ilesPerG allon = 33.8; // The average fuelef f
ciency of new U .S. cars in 2011
i

The compiler does not process comments


It ignores everything from a //delimiter to the end of
the line.

Comments
For longer comment, enclose it between /* and */
delimiters.
The compiler ignores these delimiters and everything in
between.

Example of longer comments


/* In m ost countries, fuelef f
ciency is m easured in
i
liters per hundred kilom eter. Perhaps that is m ore
useful it tells you how m uch gas you need to
purchase to drive a given distance. H ere is the
conversion form ula. */
double fuelEf f
ciency = 235.214583 / m ilesPerG allon;
i

Assignment
Use the assignment operator (= ) to change the value
of a variable.
You have the following variable declaration
int w idth = 10;

To change the value of the variable, assign the new


value
w idth = 20;

Figure 2 Assigning a New Value to a Variable

Assignment
It is an error to use a variable that has never had a
value assigned to it:
int height;
int w idth = height; // ERRO R - uninitialized variable height

The compiler will complain about an "uninitialized variable"

Figure 3 An Uninitialized Variable


Remedy: assign a value to the variable before you use it.
int height;
int w idth = height; // O K

All variables must be initialized before you access them.

Assignment
The right-hand side of the = symbol can be a
mathematical expression:
w idth = height + 10;

This means
1. compute the value of height + 10
2. store that value in the variable width
w idth = w idth + 10

The assignment operator = does not denote


mathematical equality.

Assignment

Figure 4 Executing the Statement w idth = w idth + 10

Syntax 2.2 Assignment

Self Check 2.3


What is wrong with the following variable
declaration?
int m iles per gallon = 39.4

Answer: There are three errors:


1. You cannot have spaces in variable names.
2. The variable type should be double because it holds a
fractional value.
3. There is a semicolon missing at the end of the statement.

Self Check 2.4


Declare and initialize two variables, unitPrice and
quantity, to contain the unit price of a single item and the
number of items purchased. Use reasonable initial values.

Answer:
double unitPrice = 1.95;
int quantity = 2;

Self Check 2.5


Use the variables declared in Self Check 4 to
display the total purchase price.
Answer:
System .out.print("Totalprice: ");
System .out.println(unitPrice * quantity);

Self Check 2.6


What are the types of the values 0 and "0"?
Answer: int and String

Self Check 2.7


Which number type would you use for storing the area of a circle?

Answer: double

Self Check 2.8


Which of the following are legal identifiers?
G reeting1
g
void
101dalm atians
H ello, W orld
< greeting>

Answer: Only the first two are legal identifiers.

Self Check 2.9


Declare a variable to hold your name. Use camel
case in the variable name.
Answer:
String m yN am e = "John Q . Public";

Self Check 2.10


Is 12 = 12 a valid expression in the Java language?
Answer: No, the left-hand side of the = operator
must be a variable.

Self Check 2.11


How do you change the value of the greeting variable to "H ello, N ina!"?

Answer:
greeting = "H ello, N ina!";

Note that
String greeting = "H ello,N ina!";

is not the right answerthat statement declares a new


variable

Self Check 2.12


How would you explain assignment using the
parking space analogy?
Answer: Assignment would occur when one car is
replaced by another in the parking space.

Conditionals and Loops


Now we will examine programming statements
that allow us to:
make decisions
repeat processing steps in a loop

Chapter 5 focuses on:

boolean expressions
the if and if-else statements
comparing data
while loops
iterators
more drawing techniques
more GUI components
Copyright 2012 Pearson Education, Inc.

Outline
Boolean Expressions
The if Statement
Comparing Data
The while Statement
Iterators
The ArrayList Class
Determining Event Sources
Check Boxes and Radio Buttons

Copyright 2012 Pearson Education, Inc.

Flow of Control
Unless specified otherwise, the order of statement
execution through a method is linear: one after
another
Some programming statements allow us to make
decisions and perform repetitions
These decisions are based on boolean expressions
(also called conditions) that evaluate to true or false
The order of statement execution is called the flow
of control
Copyright 2012 Pearson Education, Inc.

Conditional Statements
A conditional statement lets us choose which
statement will be executed next
They are sometimes called selection statements
Conditional statements give us the power to make
basic decisions
The Java conditional statements are the:
if and if-else statement
switch statement
We'll explore the switch statement in Chapter 6
Copyright 2012 Pearson Education, Inc.

Boolean Expressions
A condition often uses one of Java's equality
operators or relational operators, which all return
boolean results:
==
!=
<
>
<=
>=

equal to
not equal to
less than
greater than
less than or equal to
greater than or equal to

Note the difference between the equality operator


(==) and the assignment operator (=)
Copyright 2012 Pearson Education, Inc.

Boolean Expressions
An if statement with its boolean condition:
if (sum > MAX)
delta = sum MAX;

First, the condition is evaluated: the value of sum is


either greater than the value of MAX, or it is not
If the condition is true, the assignment statement is
executed; if it isn't, it is skipped
See Age.java

Copyright 2012 Pearson Education, Inc.

//********************************************************************
// Age.java
Author: Lewis/Loftus
//
// Demonstrates the use of an if statement.
//********************************************************************
import java.util.Scanner;
public class Age
{
//----------------------------------------------------------------// Reads the user's age and prints comments accordingly.
//----------------------------------------------------------------public static void main (String[] args)
{
final int MINOR = 21;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter your age: ");
int age = scan.nextInt();
continue

Copyright 2012 Pearson Education, Inc.

continue
System.out.println ("You entered: " + age);
if (age < MINOR)
System.out.println ("Youth is a wonderful thing. Enjoy.");
System.out.println ("Age is a state of mind.");
}
}

Copyright 2012 Pearson Education, Inc.

Sample Run
continue

Enter your age: 47


You entered: 47
Age is a state of mind.

System.out.println ("You entered: " + age);


if (age < MINOR)
System.out.println ("Youth is a wonderful thing. Enjoy.");
System.out.println ("Age is a state of mind.");
}
}

Another Sample Run


Enter your age: 12
You entered: 12
Youth is a wonderful thing. Enjoy.
Age is a state of mind.

Copyright 2012 Pearson Education, Inc.

Logical Operators
Boolean expressions can also use the following
logical operators:
! Logical NOT
&& Logical AND
|| Logical OR

They all take boolean operands and produce


boolean results
Logical NOT is a unary operator (it operates on one
operand)
Logical AND and logical OR are binary operators
(each operates on two operands)
Copyright 2012 Pearson Education, Inc.

Logical NOT
The logical NOT operation is also called logical
negation or logical complement
If some boolean condition a is true, then !a is false;
if a is false, then !a is true
Logical expressions can be shown using a truth
table:
a

!a

true

false

false

true

Copyright 2012 Pearson Education, Inc.

Logical AND and Logical OR


The logical AND expression
a && b
is true if both a and b are true, and false otherwise
The logical OR expression
a || b
is true if a or b or both are true, and false otherwise

Copyright 2012 Pearson Education, Inc.

Logical AND and Logical OR


A truth table shows all possible true-false
combinations of the terms
Since && and || each have two operands, there
are four possible combinations of conditions a and
b
a

a && b

a || b

true

true

true

true

true

false

false

true

false

true

false

true

false

false

false

false

Copyright 2012 Pearson Education, Inc.

Logical Operators
Expressions that use logical operators can form
complex conditions
if (total < MAX+5 && !found)
System.out.println ("Processing");

All logical operators have lower precedence than


the relational operators
The ! operator has higher precedence than && and
||

Copyright 2012 Pearson Education, Inc.

Boolean Expressions
Specific expressions can be evaluated using truth
tables
total < MAX

found

!found

total < MAX && !found

false

false

true

false

false

true

false

false

true

false

true

true

true

true

false

false

Copyright 2012 Pearson Education, Inc.

Short-Circuited Operators
The processing of && and || is short-circuited
If the left operand is sufficient to determine the
result, the right operand is not evaluated
if (count != 0 && total/count > MAX)
System.out.println ("Testing.");

This type of processing should be used carefully

Copyright 2012 Pearson Education, Inc.

Outline
Boolean Expressions
The if Statement
Comparing Data
The while Statement
Iterators
The ArrayList Class
Determining Event Sources
Check Boxes and Radio Buttons

Copyright 2012 Pearson Education, Inc.

The if Statement
Let's now look at the if statement in more detail
The if statement has the following syntax:

if is a Java
reserved word

The condition must be a


boolean expression. It
must
evaluate to either true
or false.
if ( condition )
statement;

If the condition is true, the statement is executed.


If it is false, the statement is skipped.
Copyright 2012 Pearson Education, Inc.

Logic of an if statement

condition
evaluated
true
false
statement

Copyright 2012 Pearson Education, Inc.

Indentation
The statement controlled by the if statement is
indented to indicate that relationship
The use of a consistent indentation style makes a
program easier to read and understand
The compiler ignores indentation, which can lead to
errors if the indentation is not correct
"Always code as if the person who ends up
maintaining your code will be a violent
psychopath who knows where you live."
-- Martin Golding

Copyright 2012 Pearson Education, Inc.

Quick Check
What do the following statements do?
if (total != stock + warehouse)
inventoryError = true;

if (found || !done)
System.out.println("Ok");

Copyright 2012 Pearson Education, Inc.

Quick Check
What do the following statements do?
if (total != stock + warehouse)
inventoryError = true;
Sets the boolean variable to true if the value of total
is not equal to the sum of stock and warehouse
if (found || !done)
System.out.println("Ok");
Prints "Ok" if found is true or done is false

Copyright 2012 Pearson Education, Inc.

The if-else Statement


An else clause can be added to an if statement to
make an if-else statement
if ( condition )
statement1;
else
statement2;

If the condition is true, statement1 is executed; if


the condition is false, statement2 is executed
One or the other will be executed, but not both
See Wages.java
Copyright 2012 Pearson Education, Inc.

//********************************************************************
// Wages.java
Author: Lewis/Loftus
//
// Demonstrates the use of an if-else statement.
//********************************************************************
import java.text.NumberFormat;
import java.util.Scanner;
public class Wages
{
//----------------------------------------------------------------// Reads the number of hours worked and calculates wages.
//----------------------------------------------------------------public static void main (String[] args)
{
final double RATE = 8.25; // regular pay rate
final int STANDARD = 40;
// standard hours in a work week
Scanner scan = new Scanner (System.in);
double pay = 0.0;
continue

Copyright 2012 Pearson Education, Inc.

continue
System.out.print ("Enter the number of hours worked: ");
int hours = scan.nextInt();
System.out.println ();
// Pay overtime at "time and a half"
if (hours > STANDARD)
pay = STANDARD * RATE + (hours-STANDARD) * (RATE * 1.5);
else
pay = hours * RATE;
NumberFormat fmt = NumberFormat.getCurrencyInstance();
System.out.println ("Gross earnings: " + fmt.format(pay));
}
}

Copyright 2012 Pearson Education, Inc.

continue

Sample Run

System.out.print
("Enter
the of
number
of worked:
hours worked:
Enter the
number
hours
46 ");
int hours = scan.nextInt();

Gross earnings: $404.25

System.out.println ();

// Pay overtime at "time and a half"


if (hours > STANDARD)
pay = STANDARD * RATE + (hours-STANDARD) * (RATE * 1.5);
else
pay = hours * RATE;
NumberFormat fmt = NumberFormat.getCurrencyInstance();
System.out.println ("Gross earnings: " + fmt.format(pay));
}
}

Copyright 2012 Pearson Education, Inc.

Logic of an if-else statement

condition
evaluated
true
statement1

false
statement2

Copyright 2012 Pearson Education, Inc.

The Coin Class


Let's look at an example that uses a class that
represents a coin that can be flipped
Instance data is used to indicate which face (heads
or tails) is currently showing
See CoinFlip.java
See Coin.java

Copyright 2012 Pearson Education, Inc.

//********************************************************************
// CoinFlip.java
Author: Lewis/Loftus
//
// Demonstrates the use of an if-else statement.
//********************************************************************
public class CoinFlip
{
//----------------------------------------------------------------// Creates a Coin object, flips it, and prints the results.
//----------------------------------------------------------------public static void main (String[] args)
{
Coin myCoin = new Coin();
myCoin.flip();
System.out.println (myCoin);
if (myCoin.isHeads())
System.out.println ("You win.");
else
System.out.println ("Better luck next time.");
}
}

Copyright 2012 Pearson Education, Inc.

Sample Run

//********************************************************************
// CoinFlip.java
Author: Lewis/Loftus
Tails
//
// Demonstrates the use
of anluck
if-else
Better
nextstatement.
time.
//********************************************************************
public class CoinFlip
{
//----------------------------------------------------------------// Creates a Coin object, flips it, and prints the results.
//----------------------------------------------------------------public static void main (String[] args)
{
Coin myCoin = new Coin();
myCoin.flip();
System.out.println (myCoin);
if (myCoin.isHeads())
System.out.println ("You win.");
else
System.out.println ("Better luck next time.");
}
}

Copyright 2012 Pearson Education, Inc.

//********************************************************************
// Coin.java
Author: Lewis/Loftus
//
// Represents a coin with two sides that can be flipped.
//********************************************************************
public class Coin
{
private final int HEADS = 0;
private final int TAILS = 1;
private int face;
//----------------------------------------------------------------// Sets up the coin by flipping it initially.
//----------------------------------------------------------------public Coin ()
{
flip();
}
continue

Copyright 2012 Pearson Education, Inc.

continue
//----------------------------------------------------------------// Flips the coin by randomly choosing a face value.
//----------------------------------------------------------------public void flip ()
{
face = (int) (Math.random() * 2);
}
//----------------------------------------------------------------// Returns true if the current face of the coin is heads.
//----------------------------------------------------------------public boolean isHeads ()
{
return (face == HEADS);
}
continue

Copyright 2012 Pearson Education, Inc.

continue
//----------------------------------------------------------------// Returns the current face of the coin as a string.
//----------------------------------------------------------------public String toString()
{
String faceName;
if (face == HEADS)
faceName = "Heads";
else
faceName = "Tails";
return faceName;
}
}

Copyright 2012 Pearson Education, Inc.

Indentation Revisited
Remember that indentation is for the human
reader, and is ignored by the compiler
if (depth >= UPPER_LIMIT)
delta = 100;
else
System.out.println("Reseting Delta");
delta = 0;

Despite what the indentation implies, delta will be


set to 0 no matter what

Copyright 2012 Pearson Education, Inc.

Block Statements
Several statements can be grouped together into a
block statement delimited by braces
A block statement can be used wherever a
statement is called for in the Java syntax rules
if (total > MAX)
{
System.out.println ("Error!!");
errorCount++;
}

Copyright 2012 Pearson Education, Inc.

Block Statements
The if clause, or the else clause, or both, could
govern block statements
if (total > MAX)
{
System.out.println ("Error!!");
errorCount++;
}
else
{
System.out.println ("Total: " + total);
current = total*2;
}

See Guessing.java
Copyright 2012 Pearson Education, Inc.

//********************************************************************
// Guessing.java
Author: Lewis/Loftus
//
// Demonstrates the use of a block statement in an if-else.
//********************************************************************
import java.util.*;
public class Guessing
{
//----------------------------------------------------------------// Plays a simple guessing game with the user.
//----------------------------------------------------------------public static void main (String[] args)
{
final int MAX = 10;
int answer, guess;
Scanner scan = new Scanner (System.in);
Random generator = new Random();
answer = generator.nextInt(MAX) + 1;
continue

Copyright 2012 Pearson Education, Inc.

continue
System.out.print ("I'm thinking of a number between 1 and "
+ MAX + ". Guess what it is: ");
guess = scan.nextInt();
if (guess == answer)
System.out.println ("You got it! Good guessing!");
else
{
System.out.println ("That is not correct, sorry.");
System.out.println ("The number was " + answer);
}
}
}

Copyright 2012 Pearson Education, Inc.

continue
Sample
Run
System.out.print
("I'mbetween
thinking1ofand
a number
between
1 and
I'm thinking
of a number
10. Guess
what
it "is: 6
+ MAX + ". Guess what it is: ");
That is not correct, sorry.
The number was 9
guess = scan.nextInt();

if (guess == answer)
System.out.println ("You got it! Good guessing!");
else
{
System.out.println ("That is not correct, sorry.");
System.out.println ("The number was " + answer);
}
}
}

Copyright 2012 Pearson Education, Inc.

Nested if Statements
The statement executed as a result of an if or
else clause could be another if statement
These are called nested if statements
An else clause is matched to the last unmatched
if (no matter what the indentation implies)
Braces can be used to specify the if statement to
which an else clause belongs
See MinOfThree.java

Copyright 2012 Pearson Education, Inc.

//********************************************************************
// MinOfThree.java
Author: Lewis/Loftus
//
// Demonstrates the use of nested if statements.
//********************************************************************
import java.util.Scanner;
public class MinOfThree
{
//----------------------------------------------------------------// Reads three integers from the user and determines the smallest
// value.
//----------------------------------------------------------------public static void main (String[] args)
{
int num1, num2, num3, min = 0;
Scanner scan = new Scanner (System.in);
System.out.println ("Enter three integers: ");
num1 = scan.nextInt();
num2 = scan.nextInt();
num3 = scan.nextInt();
continue

Copyright 2012 Pearson Education, Inc.

continue
if (num1 < num2)
if (num1 < num3)
min = num1;
else
min = num3;
else
if (num2 < num3)
min = num2;
else
min = num3;
System.out.println ("Minimum value: " + min);
}
}

Copyright 2012 Pearson Education, Inc.

Sample Run

continue
if (num1 < num2)
if (num1 < num3)
min = num1;
else
min = num3;
else
if (num2 < num3)
min = num2;
else
min = num3;

Enter three integers:


84 69 90
Minimum value: 69

System.out.println ("Minimum value: " + min);


}
}

Copyright 2012 Pearson Education, Inc.

Outline
Boolean Expressions
The if Statement
Comparing Data
The while Statement
Iterators
The ArrayList Class
Determining Event Sources
Check Boxes and Radio Buttons

Copyright 2012 Pearson Education, Inc.

Comparing Data
When comparing data using boolean expressions,
it's important to understand the nuances of certain
data types
Let's examine some key situations:

Comparing floating point values for equality


Comparing characters
Comparing strings (alphabetical order)
Comparing object vs. comparing object references

Copyright 2012 Pearson Education, Inc.

Comparing Float Values


You should rarely use the equality operator (==)
when comparing two floating point values (float
or double)
Two floating point values are equal only if their
underlying binary representations match exactly
Computations often result in slight differences that
may be irrelevant
In many situations, you might consider two floating
point numbers to be "close enough" even if they
aren't exactly equal
Copyright 2012 Pearson Education, Inc.

Comparing Float Values


To determine the equality of two floats, use the
following technique:
if (Math.abs(f1 - f2) < TOLERANCE)
System.out.println ("Essentially equal");

If the difference between the two floating point


values is less than the tolerance, they are
considered to be equal
The tolerance could be set to any appropriate level,
such as 0.000001
Copyright 2012 Pearson Education, Inc.

Comparing Characters
As we've discussed, Java character data is based
on the Unicode character set
Unicode establishes a particular numeric value for
each character, and therefore an ordering
We can use relational operators on character data
based on this ordering
For example, the character '+' is less than the
character 'J' because it comes before it in the
Unicode character set
Appendix C provides an overview of Unicode
Copyright 2012 Pearson Education, Inc.

Comparing Characters
In Unicode, the digit characters (0-9) are contiguous
and in order
Likewise, the uppercase letters (A-Z) and lowercase
letters (a-z) are contiguous and in order
Characters

UnicodeValues

09

48through57

AZ

65through90

az

97through122

Copyright 2012 Pearson Education, Inc.

Comparing Strings
Remember that in Java a character string is an
object
The equals method can be called with strings to
determine if two strings contain exactly the same
characters in the same order
The equals method returns a boolean result
if (name1.equals(name2))
System.out.println ("Same name");

Copyright 2012 Pearson Education, Inc.

Comparing Strings
We cannot use the relational operators to compare
strings
The String class contains the compareTo
method for determining if one string comes before
another
A call to name1.compareTo(name2)
returns zero if name1 and name2 are equal (contain the
same characters)
returns a negative value if name1 is less than name2
returns a positive value if name1 is greater than name2
Copyright 2012 Pearson Education, Inc.

Comparing Strings
Because comparing characters and strings is based
on a character set, it is called a lexicographic
ordering
int result = name1.comareTo(name2);
if (result < 0)
System.out.println (name1 + "comes first");
else
if (result == 0)
System.out.println ("Same name");
else
System.out.println (name2 + "comes first");

Copyright 2012 Pearson Education, Inc.

Lexicographic Ordering
Lexicographic ordering is not strictly alphabetical
when uppercase and lowercase characters are
mixed
For example, the string "Great" comes before the
string "fantastic" because all of the uppercase
letters come before all of the lowercase letters in
Unicode
Also, short strings come before longer strings with
the same prefix (lexicographically)
Therefore "book" comes before "bookcase"
Copyright 2012 Pearson Education, Inc.

Comparing Objects
The == operator can be applied to objects it
returns true if the two references are aliases of each
other
The equals method is defined for all objects, but
unless we redefine it when we write a class, it has
the same semantics as the == operator
It has been redefined in the String class to
compare the characters in the two strings
When you write a class, you can redefine the
equals method to return true under whatever
conditions are appropriate
Copyright 2012 Pearson Education, Inc.

Outline
Boolean Expressions
The if Statement
Comparing Data
The while Statement
Iterators
The ArrayList Class
Determining Event Sources
Check Boxes and Radio Buttons

Copyright 2012 Pearson Education, Inc.

Repetition Statements
Repetition statements allow us to execute a
statement multiple times
Often they are referred to as loops
Like conditional statements, they are controlled by
boolean expressions
Java has three kinds of repetition statements:
while, do, and for loops
The do and for loops are discussed in Chapter 6

Copyright 2012 Pearson Education, Inc.

The while Statement


A while statement has the following syntax:
while ( condition )
statement;

If the condition is true, the statement is


executed
Then the condition is evaluated again, and if it is
still true, the statement is executed again
The statement is executed repeatedly until the
condition becomes false
Copyright 2012 Pearson Education, Inc.

Logic of a while Loop

condition
evaluated
true

false

statement

Copyright 2012 Pearson Education, Inc.

The while Statement


An example of a while statement:
int count = 1;
while (count <= 5)
{
System.out.println (count);
count++;
}

If the condition of a while loop is false initially, the


statement is never executed
Therefore, the body of a while loop will execute
zero or more times
Copyright 2012 Pearson Education, Inc.

Sentinel Values
Let's look at some examples of loop processing
A loop can be used to maintain a running sum
A sentinel value is a special input value that
represents the end of input
See Average.java

Copyright 2012 Pearson Education, Inc.

//********************************************************************
// Average.java
Author: Lewis/Loftus
//
// Demonstrates the use of a while loop, a sentinel value, and a
// running sum.
//********************************************************************
import java.text.DecimalFormat;
import java.util.Scanner;
public class Average
{
//----------------------------------------------------------------// Computes the average of a set of values entered by the user.
// The running sum is printed as the numbers are entered.
//----------------------------------------------------------------public static void main (String[] args)
{
int sum = 0, value, count = 0;
double average;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter an integer (0 to quit): ");
value = scan.nextInt();
continue
Copyright 2012 Pearson Education, Inc.

continue
while (value != 0)
{
count++;

// sentinel value of 0 to terminate loop

sum += value;
System.out.println ("The sum so far is " + sum);
System.out.print ("Enter an integer (0 to quit): ");
value = scan.nextInt();
}
continue

Copyright 2012 Pearson Education, Inc.

continue
System.out.println ();
if (count == 0)
System.out.println ("No values were entered.");
else
{
average = (double)sum / count;
DecimalFormat fmt = new DecimalFormat ("0.###");
System.out.println ("The average is " + fmt.format(average));
}
}
}

Copyright 2012 Pearson Education, Inc.

continue

Sample Run

Enter an integer (0 to quit): 25


The sum so far is 25
an integer (0 to quit): 164
if (count ==Enter
0)
The sum so("No
farvalues
is 189
System.out.println
were entered.");
else
Enter an integer (0 to quit): -14
{
The sum so far is 175
average =Enter
(double)sum
/ count;
an integer
(0 to quit): 84
The sum so far is 259
DecimalFormat fmt = new DecimalFormat ("0.###");
Enter an integer
(0 toisquit):
12
System.out.println
("The average
" + fmt.format(average));
The sum so far is 271
}
Enter an integer (0 to quit): -35
The sum so far is 236
Enter an integer (0 to quit): 0
System.out.println ();

}
}

The average is 39.333

Copyright 2012 Pearson Education, Inc.

Input Validation
A loop can also be used for input validation, making
a program more robust
It's generally a good idea to verify that input is valid
(in whatever sense) when possible
See WinPercentage.java

Copyright 2012 Pearson Education, Inc.

//********************************************************************
// WinPercentage.java
Author: Lewis/Loftus
//
// Demonstrates the use of a while loop for input validation.
//********************************************************************
import java.text.NumberFormat;
import java.util.Scanner;
public class WinPercentage
{
//----------------------------------------------------------------// Computes the percentage of games won by a team.
//----------------------------------------------------------------public static void main (String[] args)
{
final int NUM_GAMES = 12;
int won;
double ratio;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the number of games won (0 to "
+ NUM_GAMES + "): ");
won = scan.nextInt();
continue
Copyright 2012 Pearson Education, Inc.

continue
while (won < 0 || won > NUM_GAMES)
{
System.out.print ("Invalid input. Please reenter: ");
won = scan.nextInt();
}
ratio = (double)won / NUM_GAMES;
NumberFormat fmt = NumberFormat.getPercentInstance();
System.out.println ();
System.out.println ("Winning percentage: " + fmt.format(ratio));
}
}

Copyright 2012 Pearson Education, Inc.

continue

Sample Run
Enter the number of games won (0 to 12): -5

while (won < 0 || won > NUM_GAMES)


Invalid input. Please reenter: 13
{
Invalid input.
Pleaseinput.
reenter:
7 reenter: ");
System.out.print
("Invalid
Please
won = scan.nextInt();
}
Winning percentage: 58%
ratio = (double)won / NUM_GAMES;
NumberFormat fmt = NumberFormat.getPercentInstance();
System.out.println ();
System.out.println ("Winning percentage: " + fmt.format(ratio));
}
}

Copyright 2012 Pearson Education, Inc.

Infinite Loops
The body of a while loop eventually must make
the condition false
If not, it is called an infinite loop, which will execute
until the user interrupts the program
This is a common logical error
You should always double check the logic of a
program to ensure that your loops will terminate
normally

Copyright 2012 Pearson Education, Inc.

Infinite Loops
An example of an infinite loop:
int count = 1;
while (count <= 25)
{
System.out.println (count);
count = count - 1;
}

This loop will continue executing until interrupted


(Control-C) or until an underflow error occurs

Copyright 2012 Pearson Education, Inc.

Control Structures
Sequential execution
Statements are normally executed one after the
other in the order in which they are written

Transfer of control
Specifying the next statement to execute that is not
necessarily the next one in order
Can be performed by the goto statement
Structured programming eliminated goto
statements

125

Control Structures (Cont.)


Bohm and Jacopinis research
Demonstrated that goto statements were unnecessary
Demonstrated that all programs could be written with
three control structures
The sequence structure,
The selection structure and
The repetition structure

126

Control Structures (Cont.)


UML activity diagram (www.uml.org)
Models the workflow (or activity) of a part of a software
system
Action-state symbols (rectangles with their sides
replaced with outward-curving arcs)
represent action expressions specifying actions to
perform
Diamonds
Decision symbols (explained in Section 4.5)
Merge symbols (explained in Section 4.7)

127

Control Structures (Cont.)


Small circles
Solid circle represents the activitys initial state
Solid circle surrounded by a hollow circle represents
the activitys final state
Transition arrows
Indicate the order in which actions are performed
Notes (rectangles with the upper-right corners folded
over)
Explain the purposes of symbols (like comments in
Java)
Are connected to the symbols they describe by dotted
lines
128

| Sequence structure activity


diagram.
Fig. 4.1

129

Control Structures (Cont.)


Selection Statements
if statement
Single-selection statement
ifelse statement
Double-selection statement
switch statement
Multiple-selection statement

130

Control Structures (Cont.)


Repetition statements
Also known as looping statements
Repeatedly performs an action while its loop-continuation
condition remains true
while statement
Performs the actions in its body zero or more times
dowhile statement
Performs the actions in its body one or more times
for statement
Performs the actions in its body zero or more times

131

Control Structures (Cont.)


Java has three kinds of control structures

Sequence statement,
Selection statements (three types) and
Repetition statements (three types)
All programs are composed of these control statements
Control-statement stacking
All control statements are single-entry/single-exit

Control-statement nesting

132

if Single-Selection Statement
if statements
Execute an action if the specified condition is true
Can be represented by a decision symbol (diamond) in a
UML activity diagram
Transition arrows out of a decision symbol have guard
conditions
Workflow follows the transition arrow whose guard condition
is true

133

| single-selection statement
UML activity diagram.
Fig. 4.2

if

134

ifelse Double-Selection Statement


ifelse statement
Executes one action if the specified condition is true or
a different action if the specified condition is false

Conditional Operator ( ? : )
Javas only ternary operator (takes three operands)
? : and its three operands form a conditional expression
Entire conditional expression evaluates to the second
operand if the first operand is true
Entire conditional expression evaluates to the third
operand if the first operand is false

135

Good Programming Practice 4.1

Indent both body statements of an


ifelse statement.

136

Good Programming Practice 4.2


If there are several levels of
indentation, each level should be
indented the same additional
amount of space.

137

Good Programming Practice 4.3


Conditional expressions are more
difficult to read than ifelse
statements and should be used to
replace only simple ifelse
statements that choose between two
values.

138

| else double-selection
statement UML activity diagram.
Fig. 4.3

if

139

ifelse Double-Selection Statement (Cont.)


Nested ifelse statements
ifelse statements can be put inside other ifelse
statements

Dangling-else problem
elses are always associated with the immediately
preceding if unless otherwise specified by braces { }

Blocks
Braces { } associate statements into blocks
Blocks can replace individual statements as an if body

140

ifelse Double-Selection Statement (Cont.)


Logic errors
Fatal logic errors cause a program to fail and terminate
prematurely
Nonfatal logic errors cause a program to produce
incorrect results

Empty statements
Represented by placing a semicolon ( ; ) where a
statement would normally be
Can be used as an if body

141

Common Programming Error 4.1


Forgetting one or both of the braces
that delimit a block can lead to
syntax errors or logic errors in a
program.

142

Good Programming Practice 4.4


Always using braces in an if...else
(or other) statement helps prevent their
accidental omission, especially when
adding statements to the if-part or the
else-part at a later time. To avoid
omitting one or both of the braces,
some programmers type the beginning
and ending braces of blocks before
typing the individual statements within
the braces.
143

Common Programming Error 4.2


Placing a semicolon after the condition
in an if or if...else statement leads
to a logic error in single-selection if
statements and a syntax error in
double-selection if...else statements
(when the if-part contains an actual
body statement).

144

Formulating Algorithms: Counter-Controlled


Repetition
Counter-controlled repetition
Use a counter variable to count the number of times a
loop is iterated

Integer division
The fractional part of an integer division calculation is
truncated (thrown away)

145

Pseudocode algorithm that uses counter-controlled


repetition to solve the class-average problem.

1
2
3
4
5
6
7
8
9
10
11

Set total to zero


Set grade counter to one
While grade counter is less than or equal to ten
Prompt the user to enter the next grade
Input the next grade
Add the grade into the total
Add one to the grade counter
Set the class average to the total divided by ten
Print the class average

146

Formulating Algorithms: Sentinel-Controlled


Repetition
Sentinel-controlled repetition
Also known as indefinite repetition
Use a sentinel value (also known as a signal, dummy or
flag value)
A sentinel value cannot also be a valid input value

147

Nested Loops
Similar to nested if statements, loops can be
nested as well
That is, the body of a loop can contain another loop
For each iteration of the outer loop, the inner loop
iterates completely
See PalindromeTester.java

Copyright 2012 Pearson Education, Inc.

//********************************************************************
// PalindromeTester.java
Author: Lewis/Loftus
//
// Demonstrates the use of nested while loops.
//********************************************************************
import java.util.Scanner;
public class PalindromeTester
{
//----------------------------------------------------------------// Tests strings to see if they are palindromes.
//----------------------------------------------------------------public static void main (String[] args)
{
String str, another = "y";
int left, right;
Scanner scan = new Scanner (System.in);
while (another.equalsIgnoreCase("y")) // allows y or Y
{
System.out.println ("Enter a potential palindrome:");
str = scan.nextLine();
left = 0;
right = str.length() - 1;
continue
Copyright 2012 Pearson Education, Inc.

continue
while (str.charAt(left) == str.charAt(right) && left < right)
{
left++;
right--;
}
System.out.println();
if (left < right)
System.out.println ("That string is NOT a palindrome.");
else
System.out.println ("That string IS a palindrome.");
System.out.println();
System.out.print ("Test another palindrome (y/n)? ");
another = scan.nextLine();
}
}
}

Copyright 2012 Pearson Education, Inc.

continue

Sample Run
Enter a potential
palindrome:
while (str.charAt(left)
== str.charAt(right)
&& left < right)
radar
{
left++;
right--;
That string IS a palindrome.
}
Test another palindrome (y/n)? y
Enter a potential palindrome:
was I ere I saw elba
if (leftable
< right)
System.out.println();

System.out.println ("That string is NOT a palindrome.");


else
That string IS a palindrome.
System.out.println ("That string IS a palindrome.");

Test another palindrome (y/n)? y

System.out.println();
Enter a potential palindrome:
System.out.print ("Test another palindrome (y/n)? ");
another abracadabra
= scan.nextLine();
}
}

That string is NOT a palindrome.

Test another palindrome (y/n)? n

Copyright 2012 Pearson Education, Inc.

Quick Check
How many times will the string "Here" be printed?
count1 = 1;
while (count1 <= 10)
{
count2 = 1;
while (count2 < 20)
{
System.out.println ("Here");
count2++;
}
count1++;
}
Copyright 2012 Pearson Education, Inc.

Quick Check
How many times will the string "Here" be printed?
count1 = 1;
while (count1 <= 10)
{
10 * 19 = 190
count2 = 1;
while (count2 < 20)
{
System.out.println ("Here");
count2++;
}
count1++;
}
Copyright 2012 Pearson Education, Inc.

Outline
Boolean Expressions
The if Statement
Comparing Data
The while Statement
Iterators
The ArrayList Class
Determining Event Sources
Check Boxes and Radio Buttons

Copyright 2012 Pearson Education, Inc.

Iterators
An iterator is an object that allows you to process a
collection of items one at a time
It lets you step through each item in turn and
process it as needed
An iterator has a hasNext method that returns true
if there is at least one more item to process
The next method returns the next item
Iterator objects are defined using the Iterator
interface, which is discussed further in Chapter 7

Copyright 2012 Pearson Education, Inc.

Iterators
Several classes in the Java standard class library
are iterators
The Scanner class is an iterator
the hasNext method returns true if there is more data to
be scanned
the next method returns the next scanned token as a
string

The Scanner class also has variations on the


hasNext method for specific data types (such as
hasNextInt)
Copyright 2012 Pearson Education, Inc.

Iterators
The fact that a Scanner is an iterator is particularly
helpful when reading input from a file
Suppose we wanted to read and process a list of
URLs stored in a file
One scanner can be set up to read each line of the
input until the end of the file is encountered
Another scanner can be set up for each URL to
process each part of the path
See URLDissector.java
Copyright 2012 Pearson Education, Inc.

//********************************************************************
// URLDissector.java
Author: Lewis/Loftus
//
// Demonstrates the use of Scanner to read file input and parse it
// using alternative delimiters.
//********************************************************************
import java.util.Scanner;
import java.io.*;
public class URLDissector
{
//----------------------------------------------------------------// Reads urls from a file and prints their path components.
//----------------------------------------------------------------public static void main (String[] args) throws IOException
{
String url;
Scanner fileScan, urlScan;
fileScan = new Scanner (new File("urls.inp"));
continue

Copyright 2012 Pearson Education, Inc.

continue
// Read and process each line of the file
while (fileScan.hasNext())
{
url = fileScan.nextLine();
System.out.println ("URL: " + url);
urlScan = new Scanner (url);
urlScan.useDelimiter("/");
// Print each part of the url
while (urlScan.hasNext())
System.out.println ("
" + urlScan.next());
System.out.println();
}
}
}

Copyright 2012 Pearson Education, Inc.

Sample Run
continue

URL: www.google.com
www.google.com

// Read and process each line of the file


URL: www.linux.org/info/gnu.html
while (fileScan.hasNext())
www.linux.org
{
url = fileScan.nextLine();
info
System.out.println
gnu.html ("URL: " + url);
urlScan = new Scanner (url);
URL: thelyric.com/calendar/
urlScan.useDelimiter("/");

thelyric.com
calendar
Print
each part of the url

//
while (urlScan.hasNext())
System.out.println
("
" + urlScan.next());
URL: www.cs.vt.edu/undergraduate/about
}
}
}

www.cs.vt.edu
System.out.println();
undergraduate
about
URL: youtube.com/watch?v=EHCRimwRGLs
youtube.com
watch?v=EHCRimwRGLs

Copyright 2012 Pearson Education, Inc.

Outline
Boolean Expressions
The if Statement
Comparing Data
The while Statement
Iterators
The ArrayList Class
Determining Event Sources
Check Boxes and Radio Buttons

Copyright 2012 Pearson Education, Inc.

The ArrayList Class


An ArrayList object stores a list of objects, and is
often processed using a loop
The ArrayList class is part of the java.util
package
You can reference each object in the list using a
numeric index
An ArrayList object grows and shrinks as
needed, adjusting its capacity as necessary

Copyright 2012 Pearson Education, Inc.

The ArrayList Class


Index values of an ArrayList begin at 0 (not 1):
0
1
2
3
4

"Bashful"
"Sleepy"
"Happy"
"Dopey"
"Doc"

Elements can be inserted and removed


The indexes of the elements adjust accordingly

Copyright 2012 Pearson Education, Inc.

ArrayList Methods
Some ArrayList methods:
boolean add (E obj)
void add (int index, E obj)
Object remove (int index)
Object get (int index)
boolean isEmpty()
int size()

Copyright 2012 Pearson Education, Inc.

The ArrayList Class


The type of object stored in the list is established
when the ArrayList object is created:
ArrayList<String> names = new ArrayList<String>();
ArrayList<Book> list = new ArrayList<Book>();

This makes use of Java generics, which provide


additional type checking at compile time
An ArrayList object cannot store primitive types,
but that's what wrapper classes are for
See Beatles.java
Copyright 2012 Pearson Education, Inc.

//********************************************************************
// Beatles.java
Author: Lewis/Loftus
//
// Demonstrates the use of a ArrayList object.
//********************************************************************
import java.util.ArrayList;
public class Beatles
{
//----------------------------------------------------------------// Stores and modifies a list of band members.
//----------------------------------------------------------------public static void main (String[] args)
{
ArrayList<String> band = new ArrayList<String>();
band.add
band.add
band.add
band.add

("Paul");
("Pete");
("John");
("George");

continue

Copyright 2012 Pearson Education, Inc.

continue
System.out.println (band);
int location = band.indexOf ("Pete");
band.remove (location);
System.out.println (band);
System.out.println ("At index 1: " + band.get(1));
band.add (2, "Ringo");
System.out.println ("Size of the band: " + band.size());
int index = 0;
while (index < band.size())
{
System.out.println (band.get(index));
index++;
}
}
}

Copyright 2012 Pearson Education, Inc.

continue

Output

System.out.println
(band);
[Paul,
Pete, John, George]
int location =[Paul,
band.indexOf
John, ("Pete");
George]
band.remove (location);

At index 1: John
Size (band);
of the band: 4
System.out.println
Paul ("At index 1: " + band.get(1));
System.out.println
John
band.add (2, "Ringo");
Ringo
System.out.println
("Size of the band: " + band.size());
George
int index = 0;
while (index < band.size())
{
System.out.println (band.get(index));
index++;
}
}
}

Copyright 2012 Pearson Education, Inc.

Outline
Boolean Expressions
The if Statement
Comparing Data
The while Statement
Iterators
The ArrayList Class
Determining Event Sources
Check Boxes and Radio Buttons

Copyright 2012 Pearson Education, Inc.

Determining Event Sources


Recall that interactive GUIs require establishing a
relationship between components and the listeners
that respond to component events
One listener object can be used to listen to two
different components
The source of the event can be determined by using
the getSource method of the event passed to the
listener
See LeftRight.java
See LeftRightPanel.java
Copyright 2012 Pearson Education, Inc.

//********************************************************************
// LeftRight.java
Authors: Lewis/Loftus
//
// Demonstrates the use of one listener for multiple buttons.
//********************************************************************
import javax.swing.JFrame;
public class LeftRight
{
//----------------------------------------------------------------// Creates the main program frame.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Left Right");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new LeftRightPanel());
frame.pack();
frame.setVisible(true);
}
}

Copyright 2012 Pearson Education, Inc.

//********************************************************************
// LeftRight.java
Authors: Lewis/Loftus
//
// Demonstrates the use of one listener for multiple buttons.
//********************************************************************
import javax.swing.JFrame;
public class LeftRight
{
//----------------------------------------------------------------// Creates the main program frame.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Left Right");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new LeftRightPanel());
frame.pack();
frame.setVisible(true);
}
}

Copyright 2012 Pearson Education, Inc.

//********************************************************************
// LeftRightPanel.java
Authors: Lewis/Loftus
//
// Demonstrates the use of one listener for multiple buttons.
//********************************************************************
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LeftRightPanel extends JPanel
{
private JButton left, right;
private JLabel label;
private JPanel buttonPanel;
continue

Copyright 2012 Pearson Education, Inc.

continue
//----------------------------------------------------------------// Constructor: Sets up the GUI.
//----------------------------------------------------------------public LeftRightPanel ()
{
left = new JButton ("Left");
right = new JButton ("Right");
ButtonListener listener = new ButtonListener();
left.addActionListener (listener);
right.addActionListener (listener);
label = new JLabel ("Push a button");
buttonPanel = new JPanel();
buttonPanel.setPreferredSize (new Dimension(200, 40));
buttonPanel.setBackground (Color.blue);
buttonPanel.add (left);
buttonPanel.add (right);
setPreferredSize (new Dimension(200, 80));
setBackground (Color.cyan);
add (label);
add (buttonPanel);
}
continue
Copyright 2012 Pearson Education, Inc.

continue
//*****************************************************************
// Represents a listener for both buttons.
//*****************************************************************
private class ButtonListener implements ActionListener
{
//-------------------------------------------------------------// Determines which button was pressed and sets the label
// text accordingly.
//-------------------------------------------------------------public void actionPerformed (ActionEvent event)
{
if (event.getSource() == left)
label.setText("Left");
else
label.setText("Right");
}
}
}

Copyright 2012 Pearson Education, Inc.

Outline
Boolean Expressions
The if Statement
Comparing Data
The while Statement
Iterators
The ArrayList Class
Determining Event Sources
Check Boxes and Radio Buttons

Copyright 2012 Pearson Education, Inc.

Check Boxes
A check box is a button that can be toggled on or off
It is represented by the JCheckBox class
Unlike a push button, which generates an action
event, a check box generates an item event
whenever it changes state
The ItemListener interface is used to define item
event listeners
A check box calls the itemStateChanged method
of the listener when it is toggled
Copyright 2012 Pearson Education, Inc.

Check Boxes
Let's examine a program that uses check boxes to
determine the style of a label's text string
It uses the Font class, which embodies a character
font's:
family name (such as Times or Courier)
style (bold, italic, or both)
font size

See StyleOptions.java
See StyleOptionsPanel.java

Copyright 2012 Pearson Education, Inc.

//********************************************************************
// StyleOptions.java
Author: Lewis/Loftus
//
// Demonstrates the use of check boxes.
//********************************************************************
import javax.swing.JFrame;
public class StyleOptions
{
//----------------------------------------------------------------// Creates and presents the program frame.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Style Options");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
StyleOptionsPanel panel = new StyleOptionsPanel();
frame.getContentPane().add (panel);
frame.pack();
frame.setVisible(true);
}
}
Copyright 2012 Pearson Education, Inc.

//********************************************************************
// StyleOptions.java
Author: Lewis/Loftus
//
// Demonstrates the use of check boxes.
//********************************************************************
import javax.swing.JFrame;
public class StyleOptions
{
//----------------------------------------------------------------// Creates and presents the program frame.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Style Options");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
StyleOptionsPanel panel = new StyleOptionsPanel();
frame.getContentPane().add (panel);
frame.pack();
frame.setVisible(true);
}
}
Copyright 2012 Pearson Education, Inc.

//********************************************************************
// StyleOptionsPanel.java
Author: Lewis/Loftus
//
// Demonstrates the use of check boxes.
//********************************************************************
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class StyleOptionsPanel extends JPanel
{
private JLabel saying;
private JCheckBox bold, italic;
continue

Copyright 2012 Pearson Education, Inc.

continue
//----------------------------------------------------------------// Sets up a panel with a label and some check boxes that
// control the style of the label's font.
//----------------------------------------------------------------public StyleOptionsPanel()
{
saying = new JLabel ("Say it with style!");
saying.setFont (new Font ("Helvetica", Font.PLAIN, 36));
bold = new JCheckBox ("Bold");
bold.setBackground (Color.cyan);
italic = new JCheckBox ("Italic");
italic.setBackground (Color.cyan);
StyleListener listener = new StyleListener();
bold.addItemListener (listener);
italic.addItemListener (listener);
add (saying);
add (bold);
add (italic);
setBackground (Color.cyan);
setPreferredSize (new Dimension(300, 100));
}
continue
Copyright 2012 Pearson Education, Inc.

continue
//*****************************************************************
// Represents the listener for both check boxes.
//*****************************************************************
private class StyleListener implements ItemListener
{
//-------------------------------------------------------------// Updates the style of the label font style.
//-------------------------------------------------------------public void itemStateChanged (ItemEvent event)
{
int style = Font.PLAIN;
if (bold.isSelected())
style = Font.BOLD;
if (italic.isSelected())
style += Font.ITALIC;
saying.setFont (new Font ("Helvetica", style, 36));
}
}
}

Copyright 2012 Pearson Education, Inc.

Radio Buttons
A group of radio buttons represents a set of
mutually exclusive options only one can be
selected at any given time
When a radio button from a group is selected, the
button that is currently "on" in the group is
automatically toggled off
To define the group of radio buttons that will work
together, each radio button is added to a
ButtonGroup object
A radio button generates an action event
Copyright 2012 Pearson Education, Inc.

Radio Buttons
Let's look at a program that uses radio buttons to
determine which line of text to display
See QuoteOptions.java
See QuoteOptionsPanel.java

Copyright 2012 Pearson Education, Inc.

//********************************************************************
// QuoteOptions.java
Author: Lewis/Loftus
//
// Demonstrates the use of radio buttons.
//********************************************************************
import javax.swing.JFrame;
public class QuoteOptions
{
//----------------------------------------------------------------// Creates and presents the program frame.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Quote Options");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
QuoteOptionsPanel panel = new QuoteOptionsPanel();
frame.getContentPane().add (panel);
frame.pack();
frame.setVisible(true);
}
}
Copyright 2012 Pearson Education, Inc.

//********************************************************************
// QuoteOptions.java
Author: Lewis/Loftus
//
// Demonstrates the use of radio buttons.
//********************************************************************
import javax.swing.JFrame;
public class QuoteOptions
{
//----------------------------------------------------------------// Creates and presents the program frame.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Quote Options");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
QuoteOptionsPanel panel = new QuoteOptionsPanel();
frame.getContentPane().add (panel);
frame.pack();
frame.setVisible(true);
}
}
Copyright 2012 Pearson Education, Inc.

//********************************************************************
// QuoteOptionsPanel.java
Author: Lewis/Loftus
//
// Demonstrates the use of radio buttons.
//********************************************************************
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class QuoteOptionsPanel extends JPanel
{
private JLabel quote;
private JRadioButton comedy, philosophy, carpentry;
private String comedyQuote, philosophyQuote, carpentryQuote;
//----------------------------------------------------------------// Sets up a panel with a label and a set of radio buttons
// that control its text.
//----------------------------------------------------------------public QuoteOptionsPanel()
{
comedyQuote = "Take my wife, please.";
philosophyQuote = "I think, therefore I am.";
carpentryQuote = "Measure twice. Cut once.";
quote = new JLabel (comedyQuote);
quote.setFont (new Font ("Helvetica", Font.BOLD, 24));
continue

Copyright 2012 Pearson Education, Inc.

continue
comedy = new JRadioButton ("Comedy", true);
comedy.setBackground (Color.green);
philosophy = new JRadioButton ("Philosophy");
philosophy.setBackground (Color.green);
carpentry = new JRadioButton ("Carpentry");
carpentry.setBackground (Color.green);
ButtonGroup group = new ButtonGroup();
group.add (comedy);
group.add (philosophy);
group.add (carpentry);
QuoteListener listener = new QuoteListener();
comedy.addActionListener (listener);
philosophy.addActionListener (listener);
carpentry.addActionListener (listener);
add
add
add
add

(quote);
(comedy);
(philosophy);
(carpentry);

setBackground (Color.green);
setPreferredSize (new Dimension(300, 100));
}
continue
Copyright 2012 Pearson Education, Inc.

continue
//*****************************************************************
// Represents the listener for all radio buttons
//*****************************************************************
private class QuoteListener implements ActionListener
{
//-------------------------------------------------------------// Sets the text of the label depending on which radio
// button was pressed.
//-------------------------------------------------------------public void actionPerformed (ActionEvent event)
{
Object source = event.getSource();
if (source == comedy)
quote.setText (comedyQuote);
else
if (source == philosophy)
quote.setText (philosophyQuote);
else
quote.setText (carpentryQuote);
}
}
}

Copyright 2012 Pearson Education, Inc.

Summary
Chapter 5 focused on:
boolean expressions
the if and if-else statements
comparing data
while loops
iterators
more drawing techniques
more GUI components

Copyright 2012 Pearson Education, Inc.

Vous aimerez peut-être aussi