Java Software Solutions Foundations of Program Design

Download Report

Transcript Java Software Solutions Foundations of Program Design

Java Software Solutions
Lewis and Loftus
Chapter 2: Objects and Primitive Data
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
1
Java Software Solutions
Lewis and Loftus
Objects and Primitive Data
• We can now explore some more fundamental
programming concepts
• Chapter 2 focuses on:
–
–
–
–
–
–
–
Chapter 3
predefined objects
primitive data
the declaration and use of variables
expressions and operator precedence
class libraries
Java applets
drawing shapes
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
2
Java Software Solutions
Lewis and Loftus
Software Engineering
• Goal
– to make software reliable and maintainable
• As the complexity of a program increases, its cost
to develop and revise grows exponentially
cost
complexity
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
3
Java Software Solutions
Lewis and Loftus
Software Components
• Programs are easier to construct and modify if
– they are made up of separate components
• A software component can be thought of
– any program element that transforms input into output
Chapter 3
Input
Component
Output
15 38
16
Compute
average
22
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
4
Java Software Solutions
Lewis and Loftus
Software Components
• Components can be combined to make larger
components
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
5
Java Software Solutions
Lewis and Loftus
Object-Oriented Programming
• Java is object-oriented language
• Programs are made from software components
called objects
• Initially, we can think of an object as
– data for it and a collection of services
• Object
– contains data and methods to provide the service
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
6
Java Software Solutions
Lewis and Loftus
Object-Oriented Programming
• Class
– A class represents a concept
– An object is defined by a class
– Multiple objects can be created from the same class
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
7
Java Software Solutions
Lewis and Loftus
Object-Oriented Programming
• A class represents a concept and
• an object represents the realization of that concept
Objects
Class
Car
My first car
John's car
Dad's car
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
8
Java Software Solutions
Lewis and Loftus
Introduction to Objects
• Recall the Lincoln program,
• We invoked the println method of the System.out
object:
System.out.println ("Whatever you are, be a good one.");
object
Chapter 3
method
Information provided to the method
(parameters)
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
9
Java Software Solutions
Lewis and Loftus
Input and Output
• Java I/O is based on input streams and output streams
• There are three predefined standard streams:
Stream
Purpose
Default Device
System.in
System.out
System.err
reading input
writing output
writing errors
keyboard
monitor
monitor
• The print and println methods write to standard output
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
10
Java Software Solutions
Lewis and Loftus
The println and print Methods
• 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 (page 53)
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
11
Java Software Solutions
Lewis and Loftus
Countdown.java
class 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!");
System.out.println ("Houston, we have a problem.");
} // method main
} // class Countdown
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
12
Java Software Solutions
Lewis and Loftus
The String Class
• Every character string is an object in Java, defined
by the String class
• Every string literal represents a String object
• A string literal cannot be broken across two lines in
a program
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
13
Java Software Solutions
Lewis and Loftus
String Concatenation and Addition
• The + operator serves two purposes
• When applied to two strings,
– they are combined into one (string concatenation)
• When applied to a string and a number,
– that value is converted to a string and concatenated
• When applied to two numeric types,
– they are added together arithmetically
• See Antarctica.java and Sum.java
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
14
Java Software Solutions
Lewis and Loftus
Antarctica.java
class Antarctica {
public static void main (String[] args) {
System.out.print ("The international " + "dialing code ");
System.out.println ("for Antarctica is " + 672);
} // method main
} // class Antarctica
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
15
Java Software Solutions
Lewis and Loftus
Sum.java
class Sum {
public static void main (String[] args) {
System.out.println ("The sum of 16 and 9 is " + (16+9));
System.out.println (“16 and 9 concatenated" + 16 + 9);
} // method main
} // class Sum
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
16
Java Software Solutions
Lewis and Loftus
Variables
• A variable is a name for a location in memory
• A variable must be declared before use
– its name and the type of information that will be held in it
data type
variable name
int total;
int count, temp, result;
Multiple variables can be created in one declaration
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
17
Java Software Solutions
Lewis and Loftus
Variables
• A variable can be given an initial value in the declaration
int sum = 0;
int base = 32, max = 149;
• When a variable is referenced in a program, its current
value is used
• See PianoKeys.java (page 60)
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
18
Java Software Solutions
Lewis and Loftus
Piano_Keys.java
class Piano_Keys {
public static void main (String[] args) {
int keys = 88;
System.out.println ("The number of piano keys: " + keys);
} // method main
} // class Piano_Keys
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
19
Java Software Solutions
Lewis and Loftus
Assignment
• An assignment statement changes the value of a variable
• The assignment operator is the = sign
total = 55;
• The expression on the right is evaluated and the result is stored
in the variable on the left
• The value that was in total is overwritten
• Assigned values must be consistent with the variable's declared
type
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
20
Java Software Solutions
Lewis and Loftus
Assignment Statements
class United_States {
public static void main (String[] args) {
int states = 13;
System.out.println ("States in 1776: " + states);
states = 50;
System.out.println ("States in 1959: " + states);
} // method main
} // class United_States
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
21
Java Software Solutions
Lewis and Loftus
Primitive Data Types
• Data type
– A set of values and the operators you can perform on them
– Each value stored in memory is associated with a
particular data type
• Primitive data types
– The Java language has 8 predefined data types
• Reserved words for primitive types:
– byte, short, int, long, float, double, boolean, char
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
22
Java Software Solutions
Lewis and Loftus
Primitive Data
• Four of them represent integers:
– byte, short, int, long
• Two of them represent floating point numbers:
– float, double
• One of them represents characters:
– char
• And one of them represents boolean values:
– boolean
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
23
Java Software Solutions
Lewis and Loftus
Integers
• There are four separate integer primitive data types
• They differ by the amount of memory used to store
them
Type
Storage Min Value
Max Value
byte
short
int
long
Chapter 3
8 bits
16 bits
32 bits
64 bits
-128
-32,768
-2,147,483,648
< -9 x 1018
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
127
32,767
2,147,483,647
> 9 x 1018
24
Java Software Solutions
Lewis and Loftus
Floating Point
• There are two floating point types:
Type
Storage
Approximate
Min Value
float
double
32 bits
64 bits
-3.4 x 1038
-1.7 x 10308
Approximate
Max Value
3.4 x 1038
1.7 x 10308
• The float type stores 7 significant digits
• The double type stores 15 significant digits
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
25
Java Software Solutions
Lewis and Loftus
Characters
• A char value stores a single character from the
Unicode character set
• A character set is an ordered list of characters
• The Unicode character set uses sixteen bits per
character, allowing for 65,536 unique characters
• Character literals are delimited by single quotes:
'a' 'X'
Chapter 3
'7'
'$'
','
'\n'
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
26
Java Software Solutions
Lewis and Loftus
Characters
• The ASCII character set is still the basis for many
other programming languages
• ASCII is a subset of Unicode, including:
uppercase letters
lowercase letters
punctuation
digits
special symbols
control characters
Chapter 3
A, B, C, …
a, b, c, …
period, semi-colon, …
0, 1, 2, …
&, |, \, …
carriage return, tab, ...
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
27
Java Software Solutions
Lewis and Loftus
Boolean
• A boolean value represents a true or false
condition
• The reserved words
– true and false are the only valid values for a boolean
type
boolean done = false;
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
28
Java Software Solutions
Lewis and Loftus
Wrappers
• Wrapper class(포장 클래스) for each primitive type
Primitive Type
Wrapper Class
int
double
char
boolean
Integer
Double
Character
Boolean
• Wrapper classes are useful in situations where you
need an object instead of a primitive type
• They also contain some useful methods
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
29
Java Software Solutions
Lewis and Loftus
Constants
• A constant is similar to a variable except that they
keep the same value throughout their existence
• They are specified using the reserved word final
• For example:
final double PI = 3.14159;
final int STUDENTS = 25;
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
30
Java Software Solutions
Lewis and Loftus
Constants
• When appropriate, constants are better than variables
– they prevent inadvertent errors because their value cannot
change
• They are better than literal values because:
– they make code more readable by giving meaning to a value
– they facilitate change because the value is only specified in
one place
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
31
Java Software Solutions
Lewis and Loftus
Expressions
• An expression is a combination of operators and
operands
– every expression has its result value.
• The arithmetic operators
+, -, *, /, %, ...
• Operands
– literal values, variables, or other sources of data
• The programmer usually
– store or print the result of an expression.
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
32
Java Software Solutions
Lewis and Loftus
Division
• Division A/B
– If A and B are both integers, the result is an integer (the
fractional part is truncated)
– If one or more operands are floating point values, the
result is a floating point value
• The remainder operator A%B
– returns the integer remainder after dividing
– The operands to the % operator must be integers
– The remainder result takes the sign of the numerator
• See Division.java
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
33
Java Software Solutions
Lewis and Loftus
Division.java
class Division {
public static void main (String[] args) {
int oper1 = 9, oper2 = 4;
double oper3 = 4.0;
System.out.println ("Integer division: " + oper1/oper2);
System.out.println ("Floating division: " + oper1/oper3);
System.out.println ("Modulus division: " + oper1%oper2);
} // method main
} // class Division
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
34
Java Software Solutions
Lewis and Loftus
Division
Chapter 3
Expression
Result
17 / 5
17.0 / 5
17 / 5.0
3
3.4
3.4
9 / 12
9.0 / 12.0
0
0.75
6 % 2
14 % 5
-14 % 5
0
4
-4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
35
Java Software Solutions
Lewis and Loftus
Operator Precedence
• Operator precedence
– The order in which operands are evaluated in an
expression
• Associativity
– Operators at the same level of precedence are evaluated
– (left to right ) or (right to left)
• Parentheses can be used to force precedence
• See Appendix D
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
36
Java Software Solutions
Lewis and Loftus
Operator Precedence
• Multiplication, division, and remainder have a
higher precedence than addition and subtraction
• Both groups associate left to right
Expression:
5 + 12 / 5 - 10 % 3
3
Order of evaluation:
Result:
Chapter 3
1
4
2
6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
37
Java Software Solutions
Lewis and Loftus
Operator Precedence
• What is the order of evaluation in the following
expressions?
a + b + c + d + e
1
2
3
4
a + b * c - d / e
3
1
4
2
a / (b + c) - d % e
2
1
4
3
a / (b * (c + (d - e)))
4
3
2
1
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
38
Java Software Solutions
Lewis and Loftus
Operator Precedence
Chapter 3
Expression
Result
2+3*4/2
8
3 * 13 + 2
(3 * 13) + 2
3 * (13 + 2)
41
41
45
4 * (11 - 6) * (-8 + 10)
40
(5 * (4 - 1)) / 2
7
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
39
Java Software Solutions
Lewis and Loftus
Assignment Revisited
• The assignment operator has a lower precedence
than the arithmetic operators
First the expression on the right hand
side of the = operator is evaluated
answer
=
4
sum / 4 + MAX * lowest;
1
3
2
Then the result is stored in the
variable on the left hand side
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
40
Java Software Solutions
Lewis and Loftus
Assignment Revisited
• The right and left hand sides of an assignment
statement can contain the same variable
First, one is added to the
original value of count
count
=
count + 1;
Then the result is stored back into count
(overwriting the original value)
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
41
Java Software Solutions
Lewis and Loftus
Data Conversions
• Sometimes it is convenient to convert data from one
type to another
• For example, we may want to treat an integer as a
floating point value during a computation
• Conversions must be handled carefully to avoid
losing information
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
42
Java Software Solutions
Lewis and Loftus
Data Conversions
• Widening conversions are safest
– they tend to go from a small data type to a larger one
(such as a short to an int)
• Narrowing conversions can lose information
– they tend to go from a large data type to a smaller one
(such as an int to a short)
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
43
Java Software Solutions
Lewis and Loftus
Data Conversions
• In Java, data conversions can occur in three ways:
– assignment conversion(ONLY WIDENING)
– arithmetic promotion(ONLY WIDENING)
– casting
• Assignment conversion occurs
– when a value of one type is assigned to a variable of
another
• Arithmetic promotion happens automatically
– when operators in expressions convert their operands
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
44
Java Software Solutions
Lewis and Loftus
Data Conversions
• Casting is the most powerful, and dangerous,
technique for conversion
• Both widening and narrowing conversions
• To cast, the type is put in parentheses in front of the
value being converted.
result = (float) total / count;
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
45
Java Software Solutions
Lewis and Loftus
Creating Objects
• A variable either holds a primitive type, or it holds a
reference to an object
• A class name can be used as a type to declare an
object reference variable
String title;
– No object has been created with this declaration
– An object reference variable holds the address of an object
• The object itself must be created separately
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
46
Java Software Solutions
Lewis and Loftus
Creating Objects
• We use the new operator to create an object
title = new String ("Java Software Solutions");
This calls the String constructor, which is
a special method that sets up the object
• Creating an object is called instantiation
• An object is an instance of a particular class
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
47
Java Software Solutions
Lewis and Loftus
Creating Objects
• Because strings are so common, we don't have to
use the new operator to create a String object
title = "Java Software Solutions";
• This is special syntax that only works for strings
• Once an object has been instantiated, we can use
the dot operator to invoke its methods
title.length()
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
48
Java Software Solutions
Lewis and Loftus
String Methods
• The String class has several methods that are
useful for manipulating strings
• Many of the methods return a value, such as an
integer or a new String object
• See the list of String methods on page 75 and in
Appendix M
• See StringMutation.java (page 77)
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
49
Java Software Solutions
Lewis and Loftus
StringMutation.java
public class StringMutation
{
public static void main (String[] args)
{
String phrase = new String ("Change is inevitable");
String mutation1, mutation2, mutation3, mutation4;
System.out.println ("Original string: \"" + phrase + "\"");
System.out.println ("Length of string: " + phrase.length());
mutation1 =
machines.");
mutation2 =
mutation3 =
mutation4 =
Chapter 3
phrase.concat (", except from vending
mutation1.toUpperCase();
mutation2.replace ('E', 'X');
mutation3.substring (3, 30);
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
50
Java Software Solutions
Lewis and Loftus
StringMutation.java
// Print each mutated string
System.out.println ("Mutation
System.out.println ("Mutation
System.out.println ("Mutation
System.out.println ("Mutation
#1:
#2:
#3:
#4:
"
"
"
"
+
+
+
+
mutation1);
mutation2);
mutation3);
mutation4);
System.out.println ("Mutated length: " + mutation4.length());
}
}
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
51
Java Software Solutions
Lewis and Loftus
Class Libraries
• The Java API is a class library,
– a group of classes that support program development
• The classes in the Java API is separated into
packages
• The System class, for example, is in package
java.lang
• Each package contains a set of classes that relate
in some way
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
52
Java Software Solutions
Lewis and Loftus
Packages
• The classes of the Java standard class library are
organized into packages
Package
Purpose
java.lang
java.applet
java.awt
javax.swing
java.net
java.util
General support
Creating applets for the web
Graphics and graphical user interfaces
Additional graphics capabilities and components
Network communication
Utilities
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
53
Java Software Solutions
Lewis and Loftus
The Java API Packages
• Other packages in the Java API:
java.applet
java.awt
java.beans
java.io
java.lang
java.math
Chapter 3
java.net
java.rmi
java.security
java.sql
java.text
java.util
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
54
Java Software Solutions
Lewis and Loftus
Importing Packages
(1) Using a class from Java API by a fully qualified name
java.lang.System.out.println ();
(2) Package can be imported using an import statement
import java.applet.*;
import java.util.Random;
• * to import all classes in a particular package
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
55
Java Software Solutions
Lewis and Loftus
The import Declaration
• All classes of the java.lang package are
automatically imported into all programs
– System or String classes
• The Random class is part of the java.util package
– It provides methods for pseudo-random numbers
– scale and shift a number into an appropriate range
• See RandomNumbers.java (page 82)
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
56
Java Software Solutions
Lewis and Loftus
RandomNumbers.java
import java.util.Random;
public class RandomNumbers
{
public static void main (String[] args)
{
Random generator = new Random();
int num1;
float num2;
num1 = generator.nextInt();
System.out.println ("A random integer: " + num1);
num1 = Math.abs (generator.nextInt()) % 10;
System.out.println ("0 to 9: " + num1);
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
57
Java Software Solutions
Lewis and Loftus
RandomNumbers.java
num1 = Math.abs (generator.nextInt()) % 20 + 10;
System.out.println ("10 to 29: " + num1);
num2 = generator.nextFloat();
System.out.println ("A random float [between 0-1]: " +
num2);
num2 = generator.nextFloat() * 6; // 0 to 5
num1 = (int) num2 + 1;
System.out.println ("1 to 6: " + num1);
}
}
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
58
Java Software Solutions
Lewis and Loftus
Class Methods
• class methods or static methods
– can be invoked through the class name, instead of through
an object of the class
• The Math class contains many static methods,
– absolute value, trigonometry functions, square root, etc.
temp = Math.cos(90) + Math.sqrt(delta);
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
59
Java Software Solutions
Lewis and Loftus
The Keyboard Class
• The Keyboard class is NOT part of the Java API
– by the authors to make reading input from the keyboard
easy
– contains several static methods for reading particular types
of data
• The Keyboard class is part of a package called cs1
• For now we will simply make use of it
– Details of the Keyboard class are explored in Chapter 8
• See Echo.java (pp 86) and Quadratic.java (pp 87)
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
60
Java Software Solutions
Lewis and Loftus
Echo.java
import cs1.Keyboard;
public class Echo
{
public static void main (String[] args)
{
String message;
System.out.println ("Enter a line of text:");
message = Keyboard.readString();
System.out.println ("You entered: \"" + message + "\"");
}
}
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
61
Java Software Solutions
Lewis and Loftus
Quadratic.java
import cs1.Keyboard;
public class Quadratic
{
public static void main (String[] args)
{
int a, b, c; // ax^2 + bx + c
System.out.print ("Enter the coefficient of x squared: ");
a = Keyboard.readInt();
System.out.print ("Enter the coefficient of x: ");
b = Keyboard.readInt();
System.out.print ("Enter the constant: ");
c = Keyboard.readInt();
double discriminant = Math.pow(b, 2) - (4 * a * c);
double root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a);
double root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a);
System.out.println ("Root #1: " + root1);
System.out.println ("Root #2: " + root2);
}
Chapter 3
}
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
62
Java Software Solutions
Lewis and Loftus
Formatting Output
• The NumberFormat class has static methods that
return a formatter object
getCurrencyInstance()
getPercentInstance()
• Each formatter object has a method called format
that returns a string with the specified information in
the appropriate format
• See Price.java (page 89)
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
63
Java Software Solutions
Lewis and Loftus
Price.java
import cs1.Keyboard;
import java.text.NumberFormat;
public class Price
{
public static void main (String[] args)
{
final double TAX_RATE = 0.06; // 6% sales tax
int quantity;
double subtotal, tax, totalCost, unitPrice;
System.out.print ("Enter the quantity: ");
quantity = Keyboard.readInt();
System.out.print ("Enter the unit price: ");
unitPrice = Keyboard.readDouble();
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
64
Java Software Solutions
Lewis and Loftus
Price.java
subtotal = quantity * unitPrice;
tax = subtotal * TAX_RATE;
totalCost = subtotal + tax;
// Print output with appropriate formatting
NumberFormat money =
NumberFormat.getCurrencyInstance();
NumberFormat percent =
NumberFormat.getPercentInstance();
System.out.println ("Subtotal: " + money.format(subtotal));
System.out.println ("Tax: " + money.format(tax) + " at "
+ percent.format(TAX_RATE));
System.out.println ("Total: " + money.format(totalCost));
}
}
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
65
Java Software Solutions
Lewis and Loftus
Formatting Output
• The DecimalFormat class can be used to format
a floating point value in generic ways
• For example, you can specify that the number
be printed to three decimal places
• The constructor of the DecimalFormat class
takes a string that represents a pattern for the
formatted number
• See CircleStats.java (page 91)
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
66
Java Software Solutions
Lewis and Loftus
CircleStats.java
import cs1.Keyboard;
import java.text.DecimalFormat;
public class CircleStats
{
public static void main (String[] args)
{
int radius;
double area, circumference;
System.out.print ("Enter the circle's radius: ");
radius = Keyboard.readInt();
area = Math.PI * Math.pow(radius, 2);
circumference = 2 * Math.PI * radius;
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
67
Java Software Solutions
Lewis and Loftus
CircleStats.java
// Round the output to three decimal places
DecimalFormat fmt = new DecimalFormat ("0.###");
System.out.println ("The circle's area: " +
fmt.format(area));
System.out.println ("The circle's circumference: "
+ fmt.format(circumference));
}
}
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
68
Java Software Solutions
Lewis and Loftus
Input and Output
• The Java API allows you to create many kinds of
streams to perform various kinds of I/O
• To read character strings, we will convert the
System.in stream to another kind of stream using:
BufferedReader stdin = new BufferedReader
(new InputStreamReader (System.in));
• This declaration creates a new stream called stdin
• We will discuss object creation in more detail later
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
69
Java Software Solutions
Lewis and Loftus
Numeric Input
• Converting a string that holds an integer into the
integer value using Integer wrapper class:
value = Integer.parseInt (my_string);
• A value can be read and converted in one line:
num = Integer.parseInt (stdin.readLine());
• See Addition.java and Addition2.java
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
70
Java Software Solutions
Lewis and Loftus
Escape Sequences
• See Echo.java
• An escape sequence is a special sequence of
characters preceded by a backslash (\)
• They indicate some special purpose, such as:
Chapter 3
Escape Sequence
Meaning
\t
\n
\"
\'
\\
tab
new line
double quote
single quote
backslash
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
71
Java Software Solutions
Lewis and Loftus
Echo.java
import java.io.*;
class Echo {
public static void main (String[] args) throws IOException {
BufferedReader stdin = new BufferedReader
(new InputStreamReader(System.in));
String message;
System.out.println ("Enter a line of text:");
message = stdin.readLine();
System.out.println ("You entered: \"" + message + "\"");
} // method main
} // class Echo
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
72
Java Software Solutions
Lewis and Loftus
Java Applets
• A Java applet
– a Java program that is intended to be sent across a
network and executed using a Web browser
• A Java application is a stand alone program
– Applications have a main method, but applets do not
• Special methods of applets
– The paint method, for instance, is automatically executed
and is used to draw the applets contents
• Applets are derived from the java.applet.Applet
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
73
Java Software Solutions
Lewis and Loftus
Java Applets
• Links to applets can be embedded in HTML
documents
– actually the bytecode version of the program that is
transported across the web
• The applet is executed by a Java interpreter that is
part of the browser(Netscape or Explorer)
• Appletviewer in JDK
– appletviewer xxx.html
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
74
Java Software Solutions
Lewis and Loftus
Execution of Java Applets
local computer
Java source
code
remote
computer
Chapter 3
Java
compiler
Java
bytecode
Web browser
Java
interpreter
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
75
Java Software Solutions
Lewis and Loftus
Applets
• The paint method accepts a parameter that is an
object of the Graphics class
• A Graphics object defines a graphics context on
which we can draw shapes and text
• The Graphics class has several methods for
drawing shapes
• See Einstein.java (page 93)
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
76
Java Software Solutions
Lewis and Loftus
Einstein.java
import java.applet.Applet;
import java.awt.*;
public class Einstein extends Applet
{
// Draws a quotation by Albert Einstein among some shapes.
public void paint (Graphics page)
{
page.drawRect (50, 50, 40, 40); // square
page.drawRect (60, 80, 225, 30); // rectangle
page.drawOval (75, 65, 20, 20); // circle
page.drawLine (35, 60, 100, 120); // line
page.drawString ("Out of clutter, find simplicity.", 110, 70);
page.drawString ("-- Albert Einstein", 130, 100);
}
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
77
Java Software Solutions
Lewis and Loftus
Drawing Shapes
• A shape can be filled or unfilled, depending on
which method is invoked
– fillArc( ), fillOval( ), fillRect( )
• The method parameters specify coordinates and
sizes
• Java coordinate system has the origin in the upper
left corner
• Many shapes with curves, like an oval, are drawn
by specifying its bounding rectangle
• An arc can be thought of as a section of an oval
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
78
Java Software Solutions
Lewis and Loftus
Drawing a Line
10
150
X
20
45
Y
page.drawLine (10, 20, 150, 45);
or
page.drawLine (150, 45, 10, 20);
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
79
Java Software Solutions
Lewis and Loftus
Drawing a Rectangle
50
X
20
40
100
Y
page.drawRect (50, 20, 100, 40);
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
80
Java Software Solutions
Lewis and Loftus
Drawing an Oval
175
X
20
80
bounding
rectangle
Y
50
page.drawOval (175, 20, 50, 80);
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
81
Java Software Solutions
Lewis and Loftus
The Color Class
• A color is defined in a Java program using an object
created from the Color class
• The Color class also contains several static
predefined colors
• Every graphics context has a current foreground
color
• Every drawing surface has a background color
• See Snowman.java (page 99-100)
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
82
Java Software Solutions
Lewis and Loftus
Snowman.java
import java.applet.Applet;
import java.awt.*;
public class Snowman extends Applet
{
public void paint (Graphics page)
{
final int MID = 150;
final int TOP = 50;
setBackground (Color.cyan);
page.setColor (Color.blue);
page.fillRect (0, 175, 300, 50); // ground
page.setColor (Color.yellow);
page.fillOval (-40, -40, 80, 80); // sun
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
83
Java Software Solutions
Lewis and Loftus
Snowman.java
page.setColor (Color.white);
page.fillOval (MID-20, TOP, 40, 40);
// head
page.fillOval (MID-35, TOP+35, 70, 50); // upper torso
page.fillOval (MID-50, TOP+80, 100, 60); // lower torso
page.setColor (Color.black);
page.fillOval (MID-10, TOP+10, 5, 5); // left eye
page.fillOval (MID+5, TOP+10, 5, 5); // right eye
page.drawArc (MID-10, TOP+20, 20, 10, 190, 160); // smile
page.drawLine (MID-25, TOP+60, MID-50, TOP+40); // left arm
page.drawLine (MID+25, TOP+60, MID+55, TOP+60); // right arm
page.drawLine (MID-20, TOP+5, MID+20, TOP+5); // brim of
page.fillRect (MID-15, TOP-20, 30, 25);
// top of hat
}
}
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
84