Java Software Solutions Lewis and Loftus Chapter 3 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Program Elements -- Introduction • We can now examine the core elements of programming • Chapter 3 focuses on: – data types – variable declaration and use – operators and expressions – decisions and loops – input and output
41
Embed
Chapter 3 focuses on - University of Victoriawebhome.cs.uvic.ca/~hausi/110/book/pdf/chap03.pdf · Java Software Solutions Lewis and Loftus Chapter 3 2 Copyright 1997 by John Lewis
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
1 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Program
Elem
ents -- Introduction
•W
e can now exam
ine the core elements of program
ming
•C
hapter 3 focuses on:
–data types
–variable declaration and use
–operators and expressions
–decisions and loops
–input and output
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
2 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Prim
itive Data T
ypes
•A
da
ta typ
e is defined by a set of values and the operators you can perform
on them
•E
ach value stored in mem
ory is associated with a
particular data type
•T
he Java language has several predefined types, called p
rimitive
da
ta typ
es
•T
he following reserved w
ords represent eight different prim
itive types:
–b
yte, sh
ort
, int
, lon
g, flo
at
, do
ub
le, b
oo
lea
n, ch
ar
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
3 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Integers
•T
here are four separate integer primitive data types
•T
hey differ by the amount of m
emory used to store them
Type
byteshortintlong
Storage
8 bits16 bits32 bits64 bits
Min V
alue
-128-32,768-2,147,483,648<
-9 x 10 18
Max V
alue
12732,7672,147,483,647>
9 x 10 18
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
4 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Floating P
oint
•T
here are two floating point types:
•T
he floa
t type stores 7 significant digits
•T
he do
ub
le
type stores 15 significant digits
Type
floatdouble
Storage
32 bits64 bits
Approxim
ateM
in Value
-3.4 x 10 38
-1.7 x 10 308
Approxim
ateM
ax Value
3.4 x 10 38
1.7 x 10 308
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
5 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Characters
•A
cha
r value stores a single character from
the U
nico
de
cha
racte
r set
•A
cha
racte
r set is an ordered list of characters
•T
he Unicode character set uses sixteen bits per character,
allowing for 65,536 unique characters
•It is an international character set, containing sym
bols and characters from
many w
orld languages
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
6 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Characters
•T
he AS
CII character set is still the basis for m
any other program
ming languages
•A
SC
II is a subset of Unicode, including:
uppercase letterslow
ercase letterspunctuationdigitsspecial sym
bolscontrol characters
A, B
, C, …
a, b, c, …period, sem
i-colon, …0, 1, 2, …&
, |, \, …carriage return, tab, ...
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
7 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Boolean
•A
bo
ole
an
value represents a true or false condition
•T
hey can also be used to represent any two states, such
as a light bulb being on or off
•T
he reserved words tru
e
and false
are the only
valid values for a boolean type
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
8 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Wrappers
•F
or each primitive data type there is a corresponding
wra
pp
er cla
ss. For exam
ple:
•W
rapper classes are useful in situations where you need
an object instead of a primitive type
•T
hey also contain some useful m
ethods
Prim
itive Type
int
do
ub
lech
ar
bo
ole
an
Wrapper C
lass
Inte
ge
rD
ou
ble
Ch
ara
cter
Bo
ole
an
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
9 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Variables
•A
varia
ble is an identifier that represents a location in
mem
ory that holds a particular type of data
•V
ariables must be declared before they can be used
•T
he syntax of a variable declaration is:
d
ata
-type
varia
ble
-na
me
;
•F
or example:
int to
tal;
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
10 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Variables
•M
ultiple variables can be declared on the same line:
int to
tal, co
un
t, sum
;
•V
ariables can be initialize
d (given an initial value) in the declaration:
int to
tal =
0, co
un
t = 2
0;
floa
t un
it_p
rice =
57
.25
;
•S
ee Pia
no
_K
eys.ja
va
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
11 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Assignm
ent Statem
ents
•A
n assignment statem
ent takes the following form
:
va
riab
le-n
am
e =
e
xpre
ssion
;
•T
he expression is evaluated and the result is stored in the variable, overw
riting the value currently stored in the variable
•S
ee Un
ited
_S
tate
s.java
•T
he expression can be a single value or a more
complicated calculation
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
12 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Constants
•A
constant is similar to a variable except that they keep
the same value throughout their existence
•T
hey are specified using the reserved word
fina
l in
the declaration
•F
or example:
fina
l do
ub
le P
I = 3
.14
15
9;
fina
l int S
TU
DE
NT
S =
25
;
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
13 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Constants
•W
hen appropriate, constants are better than variables because:
–they prevent inadvertent errors because their value cannot change
•T
hey are better than literal values because:
–they m
ake code more readable by giving m
eaning to a value
–they facilitate change because the value is only specified in one place
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
14 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Input and Output
•Java I/O
is based on in
pu
t strea
ms and o
utp
ut stre
am
s
•T
here are three predefined standard streams:
•T
he prin
t and p
rintln
m
ethods write to standard
output
Stream
Syste
m.in
Syste
m.o
ut
Syste
m.e
rr
Purpose
reading inputw
riting outputw
riting errors
Default D
evice
keyboardm
onitorm
onitor
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
15 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Input and Output
•T
he Java AP
I allows you to create m
any kinds of streams
to perform various kinds of I/O
•T
o read character strings, we w
ill convert the
Syste
m.in
stream
to another kind of stream using:
Bu
ffere
dR
ea
de
r stdin
= n
ew
Bu
ffere
dR
ea
de
r
(ne
w In
pu
tStre
am
Re
ad
er (S
ystem
.in));
•T
his declaration creates a new stream
called std
in
•W
e will discuss object creation in m
ore detail later
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
16 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Escape S
equences
•S
ee Ech
o.ja
va
•A
n esca
pe
seq
ue
nce is a special sequence of characters
preceded by a backslash (\)
•T
hey indicate some special purpose, such as:
Escape S
equence
\t\n\"\'\\
Meaning
tabnew
linedouble quotesingle quotebackslash
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
17 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Buffers
•A
s you type, the characters are stored in an in
pu
t bu
ffer
•W
hen you press enter, the program begins processing the
data
•S
imilarly, output inform
ation is temporarily stored in an
ou
tpu
t bu
ffer
•T
he output buffer can be explicitly flu
she
d (sent to the screen) using the flu
sh
method
•S
ee Pyth
on
.java
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
18 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Num
eric Input
•C
onverting a string that holds an integer into the integer value can be done w
ith a method in the
Inte
ge
r w
rapper class:
valu
e =
Inte
ge
r.pa
rseIn
t (my_
string
);
•A
value can be read and converted in one line:
nu
m =
Inte
ge
r.pa
rseIn
t (stdin
.rea
dL
ine
());
•S
ee Ad
ditio
n.ja
va
and Ad
ditio
n2
.java
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
19 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Expressions
•A
n exp
ressio
n is a combination of operators and
operands
•T
he arithmetic operators include addition (
+), subtraction
(-), m
ultiplication (*), and division (/)
•O
perands can be literal values, variables, or other sources of data
•T
he programm
er determines w
hat is done with the result
of an expression (stored, printed, etc.)
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
20 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Division
•If the operands of the /
operator are both integers, the result is an integer (the fractional part is truncated)
•If one or m
ore operands to the /
operator are floating point values, the result is a floating point value
•T
he remainder operator (
%) returns the integer rem
ainder after dividing the first operand by the second
•T
he operands to the %
operator must be integers
•S
ee Divisio
n.ja
va
•T
he remainder result takes the sign of the num
erator
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
21 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Division
Expression
17
/ 51
7.0
/ 51
7 / 5
.0
9 / 1
29
.0 / 1
2.0
6 %
21
4 %
5-1
4 %
5
Result
33
.43
.400
.7504-4
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
22 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Operator P
recedence
•T
he order in which operands are evaluated in an
expression is determined by a w
ell-defined p
rece
de
nce
h
iera
rchy
•O
perators at the same level of precedence are evaluated
according to their associa
tivity (right to left or left to right)
•P
arentheses can be used to force precedence
•A
ppendix D contains a com
plete operator precedence chart for all Java operators
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
23 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Operator P
recedence
•M
ultiplication, division, and remainder have a higher
precedence than addition and subtraction
•B
oth groups associate left to right
Expression:
Order of evaluation:
Result:
5 +
12
/ 5 - 1
0 %
3
6
43
21
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
24 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Operator P
recedence
Expression
2 +
3 * 4
/ 2
3 * 1
3 +
2(3
* 13
) + 2
3 * (1
3 +
2)
4 * (1
1 - 6
) * (-8 +
10
)
(5 * (4
- 1)) / 2
Result
841
41
45
407
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
25 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
The if S
tatement
•T
he Java if state
me
nt has the follow
ing syntax:
if (co
nd
ition
)
sta
tem
en
t;
•If the boolean condition is true, the statem
ent is executed; if it is false, the statem
ent is skipped
•T
his provides basic decision making capabilities
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
26 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
The if S
tatement
statement
conditionfalse
true
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
27 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Boolean E
xpressions
•T
he condition of an if statem
ent must evaluate to a
true or false result
•Java has several equality and relational operators:
•S
ee Te
mp
era
ture
.java
Operator
==
!=<<=><=
Meaning
equal tonot equal to
less thanless than or equal to
greater thangreater than or equal to
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
28 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Block S
tatements
•S
everal statements can be grouped together into a
blo
ck sta
tem
en
t
•B
locks are delimited by braces
•A
block statement can be used w
herever a statement is
called for in the Java syntax
•S
ee Tem
pe
ratu
re2
.java
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
29 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
The if-else S
tatement
•A
n e
lse
clause can be added to an if
statement to
make it an if-e
lse sta
tem
en
t:
if (co
nd
ition
)
sta
tem
en
t1;
else
sta
tem
en
t2;
•If the condition is true, statem
ent1 is executed; if the condition is false, statem
ent2 is executed
•S
ee Tem
pe
ratu
re3
.java
and R
igh
t_T
rian
gle
.java
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
30 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
The if-else S
tatement
statement1
conditionfalse
true
statement2
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
31 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Nested if S
tatements
•T
he body of an if statem
ent or else
clause can be another if
statement
•T
hese are called n
este
d if sta
tem
en
ts
•S
ee Foo
tba
ll_C
ho
ice.ja
va
•N
ote: an else
clause is m
atched to the last unm
atched if (no m
atter what the indentation im
plies)
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
32 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
The w
hile Statem
ent
•A
wh
ile sta
tem
en
t has the following syntax:
wh
ile (
con
ditio
n)
sta
tem
en
t;
•If the condition is true, the statem
ent is executed; then the condition is evaluated again
•T
he statement is executed over and over until the
condition becomes false
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
33 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
The w
hile Statem
entstatement
conditionfalse
true
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
34 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
The w
hile Statem
ent
•If the condition of a w
hile
statem
ent is false initially, the statem
ent is never executed
•T
herefore, we say that a
wh
ile
statement executes
zero or more tim
es
•S
ee Co
un
ter.ja
va, F
acto
rs.java
, and P
ow
ers_
of_
Tw
o.ja
va
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
35 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Infinite Loops
•T
he body of a wh
ile
loop must eventually m
ake the condition false
•If not, it is an in
finite
loo
p, which w
ill execute until the user interrupts the program
•T
his is a comm
on type of logical error -- always double
check that your loops will term
inate normally
•S
ee Fo
reve
r.java
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
36 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Program
Developm
ent
•T
he creation of software involves four basic activities:
–establishing the requirem
ents
–creating a design
–im
plementing the code
–testing the im
plementation
•T
he development process is m
uch more involved that
this, but these basic steps are a good starting point
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
37 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Requirem
ents
•R
equirements specify the tasks a program
must
accomplish (w
hat to do, not how to do it)
•T
hey often address the user interface
•A
n initial set of requirements are often provided, but
usually must be critiqued, m
odified, and expanded
•It is often difficult to establish detailed, unam
biguous, com
plete requirements
•C
areful attention to the requirements can save significant
time and m
oney in the overall project
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
38 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Design
•A
program follow
s an algo
rithm
, which is a step-by-step
process for solving a problem
•T
he design specifies the algorithms and data needed
•In object-oriented developm
ent, it establishes the classes, objects, and m
ethods that are required
•T
he details of a method m
ay be expressed in p
seu
do
cod
e, which is code-like, but does not necessarily
follow any specific syntax
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
39 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Implem
entation
•Im
plementation is the process of translating a design into
source code
•M
ost novice programm
ers think that writing code is the
heart of software developm
ent, but it actually should be the least creative
•A
lmost all im
portant decisions are made during
requirements analysis and design
•Im
plementation should focus on coding details,
including style guidelines and documentation
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
40 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Testing
•A
program should be executed m
ultiple times w
ith various input in an attem
pt to find errors
•D
eb
ug
gin
g is the process of discovering the cause of a problem
and fixing it
•P
rogramm
ers often erroneously think that there is "only one m
ore bug" to fix
•T
ests should focus on design details as well as overall
requirements
Java Softw
are Solutions Lew
is and Loftus
Chapter 3
41 C
opyright 1997 by John Lewis and W
illiam Loftus. A
ll rights reserved.
Program
Developm
ent
•S
ee Ave
rag
e.ja
va
•F
ollow the process of requirem
ents analysis, design, im
plementation, and testing
•T
here are always m
ultiple ways to design and im
plement
a program
•A
ny design has advantages and disadvantages; there are alw