Download Chapter #, Title - Help-A-Bull

Document related concepts
no text concepts found
Transcript
Topics
• Chapter 2:
– Data conversion
• Chapter 3
– Object creation and object references
– The String class and its methods
– The Java standard class library
– The Math class
– Formatting output
• Chapter 5:
– Simple Flow of Control
Exercise
•
What is the value of the variable unitPrice?
int totalPrice = 12;
int quantity = 5;
double unitPrice = 0;
unitPrice = totalPrice / quantity;
Casting
• Casting is the most powerful, and dangerous,
technique for conversion
• Both widening and narrowing conversions can be
accomplished by explicitly casting a value
• To cast, the type is put in parentheses in front of
the value being converted
Casting
• For example, if total and count are integers, but we want
a floating point result when dividing them, we can cast
total:
result = (double) total / count;
• Another example:
– double num = 0.9; int result = (int) num;
– Convert 0.9 to an int value: 0, truncating any fractional part.
Exercise
•
What is the value of the variable unitPrice?
int totalPrice = 12;
int quantity = 5;
double unitPrice = 0;
unitPrice = (double)totalPrice / quantity;
Object Creation and Object References
Creating Objects
• A variable holds either a primitive type or a
reference to an object
num1
name1
38
"Steve Jobs"
Creating Objects
• A class name can be used as a type to declare an object
reference variable
String title;
• An object reference variable holds the address of an object
• The object itself must be created separately
Creating Objects
• Generally, 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
References
• An object reference can be thought of as a pointer
to the location of the object
num1
name1
38
"Steve Jobs"
Assignment Revisited
• The act of assignment takes a copy of a value
and stores it in a variable
• For primitive types:
Before:
num1
38
num2
96
num2 = num1;
After:
num1
38
num2
38
Reference Assignment
• For object references, assignment copies the
address:
Before:
name1
"Steve Jobs"
name2
"Steve Wozniak"
name2 = name1;
name1
After:
name2
"Steve Jobs"
The String Class
The String Class
• Because strings are so common, we don't have to
use the new operator to create a String object
String title = "Java Software Solutions";
• This is special syntax that works only for strings
• Each string literal (enclosed in double quotes)
represents a String object
Copyright © 2012 Pearson Education, Inc.
String Indexes
• It is occasionally helpful to refer to a particular
character within a string
• This can be done by specifying the character's
numeric index
• The indexes begin at zero in each string
• In the string "Hello", the character 'H' is at
index 0 and the 'o' is at index 4
String Methods
• Once a String object has been created, neither
its value nor its length can be changed
• However, several methods of the String class
return new String objects that are modified
versions of the original
Method
• What is a method?
– A group of statements that is given a name.
• How to invoke a method?
– When a method is invoked, only the method’s name and
the parameters are needed.
• What happens when a method is invoked?
– When a method is invoked, the flow of control transfers to
that method and the statements of that method are
executed.
• How to interpret a method listing as follows?
– int length()
Returns the number of characters in this string.
return type
method name
Invoking Methods
• We've seen that once an object has been instantiated, we
can use the dot operator to invoke its methods
String title = "Data";
int count = title.length();
• A method may return a value, which can be used in an
assignment or expression
• A method invocation can be thought of as asking an object
to perform a service
Some Methods of the String Class
• int length()
– Returns the number of characters in this string.
• String concat (String str)
– Returns a new string consisting of this string concatenated with str.
– Example: title= title.concat(" Structures");
• String toUpperCase ()
– Returns a new string identical to this string except all lowercase
letters are converted to their uppercase equivalent.
– Example: newTitle = title.toUpperCase();
Some Methods of the String Class
• String replace (char oldChar, char newChar)
– Returns a new string that is identical with this string except that every
occurrence of oldChar is replaced by newChar.
– Example: String replaced = title.replace('a', 'z');
• String substring (int beginIndex, int endIndex)
– Returns a new string that is a subset of this string starting at
beginIndex and extending through
endIndex -1. Thus the length of the substring is
endIndex – beginIndex.
– Example: String sub = title.substring(5, 7);
Exercise
• What output is produced by the following code
fragment?
String m1, m2, m3, m4;
m1 = "Programming Language";
m2 = m1.toLowerCase();
m3 = m1 + " " + "Java";
m4 = m3.replace('a', 'm');
System.out.println(m4.subString(2, 5));
Some Methods of the String Class
• int indexOf(String str)
Returns the index within this string of the first
occurrence of the specified substring.
• Exercise: Write a program that reads in a line of
text, a search string, a replace string. The program
will output a line of text with the first occurrence of
the search string changed to the replace string.
Packages
Class Libraries
• A class library is a collection of classes that we can use
when developing programs
• The Java standard class library is part of any Java
development environment; Its classes are not part of the
Java language, but we rely on them heavily
• Various classes we've already used (System , Scanner,
String) are part of the Java standard class library
Packages
• The classes of the Java standard class library are
organized into packages
• Some of the packages in the standard class library
are:
Package
Purpose
java.lang
java.awt
javax.swing
java.net
java.util
General support
Graphics and graphical user interfaces
Additional graphics capabilities
Network communication
Utilities
The import Declaration
• When you want to use a class from a package, you
can import the class, and then use just the class
name
import java.util.Scanner;
• To import all classes in a particular package, you
can use the * wildcard character
import java.util.*;
The import Declaration
• All classes of the java.lang package are imported
automatically into all programs
• It's as if all programs contain the following line:
import java.lang.*;
• That's why we didn't have to import the System or String
classes explicitly in earlier programs
The Math Class
The Math Class
• The Math class is part of the java.lang package
• The Math class contains methods that perform
various mathematical functions
• These include:
– absolute value, square root, exponentiation
– trigonometric functions
The Math Class
• The methods of the Math class are static methods (also
called class methods)
• Static methods can be invoked through the class name – no
object of the Math class is needed
value = Math.cos(90) + Math.sqrt(delta);
Some Methods of the Math Class
• static int abs (int num)
– Returns the absolute value of num.
• static double sin (double angle)
– Returns the sine of angle measured in radians.
• static double ceil (double num)
– Returns the ceiling of num, which is the smallest whole
number greater than or equal to num.
Some Methods of the Math Class
• static double pow (double num, double power)
– Returns the value num raised to the specified power.
• static double sqrt (double num)
– Returns the square root of num, which must be
positive
//********************************************************************
// Quadratic.java
Author: Lewis/Loftus
//
// Demonstrates the use of the Math class to perform a calculation
// based on user input.
//********************************************************************
import java.util.Scanner;
public class Quadratic
{
//----------------------------------------------------------------// Determines the roots of a quadratic equation.
//----------------------------------------------------------------public static void main (String[] args)
{
int a, b, c; // ax^2 + bx + c
double discriminant, root1, root2;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the coefficient of x squared: ");
a = scan.nextInt();
continued
Copyright © 2012 Pearson Education, Inc.
continued
System.out.print ("Enter the coefficient of x: ");
b = scan.nextInt();
System.out.print ("Enter the constant: ");
c = scan.nextInt();
// Use the quadratic formula to compute the roots.
// Assumes a positive discriminant.
discriminant = Math.pow(b, 2) - (4 * a * c);
root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a);
root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a);
System.out.println ("Root #1: " + root1);
System.out.println ("Root #2: " + root2);
}
}
Copyright © 2012 Pearson Education, Inc.
Imprecision of Floating-point Numbers
• Floating-point numbers are not real numbers.
There are a finite number of them.
• There are maximum and minimum values they can
represent. Most importantly, they have limited,
though large, precision and are subject to round-off
error.
Formatting Output
Formatting Output
• It is often necessary to format values in certain ways so that
they can be presented properly
• The Java standard class library contains classes that
provide formatting capabilities
• For example, a currency formatter can be used to format
5.8792 to monetary value $5.88 and a percent formatter can
be used to format 0.492 to 49%.
Copyright © 2012 Pearson Education, Inc.
Formatting Output
• The NumberFormat class allows you to format
values as currency or percentages
• The DecimalFormat class allows you to format
values based on a pattern
• Both are part of the java.text package
Formatting Output
• The NumberFormat class has static methods that return a
formatter object
NumberFormat fmt1 = NumberFormat.getCurrencyInstance();
NumberFormat fmt2 = NumberFormat.getPercentInstance();
• Each formatter object has a method called format that
returns a string with the specified information in the
appropriate format.
Formatting Output
• The fractional potion of the value will be rounded
up.
• String format (double number)
– Returns a string containing the specified number
formatted according to this object’s pattern.
//********************************************************************
// Purchase.java
Author: Lewis/Loftus
//
// Demonstrates the use of the NumberFormat class to format output.
//********************************************************************
import java.util.Scanner;
import java.text.NumberFormat;
public class Purchase
{
//----------------------------------------------------------------// Calculates the final price of a purchased item using values
// entered by the user.
//----------------------------------------------------------------public static void main (String[] args)
{
final double TAX_RATE = 0.06; // 6% sales tax
int quantity;
double subtotal, tax, totalCost, unitPrice;
Scanner scan = new Scanner (System.in);
continued
Copyright © 2012 Pearson Education, Inc.
continued
NumberFormat fmt1 = NumberFormat.getCurrencyInstance();
NumberFormat fmt2 = NumberFormat.getPercentInstance();
System.out.print ("Enter the quantity: ");
quantity = scan.nextInt();
System.out.print ("Enter the unit price: ");
unitPrice = scan.nextDouble();
subtotal = quantity * unitPrice;
tax = subtotal * TAX_RATE;
totalCost = subtotal + tax;
// Print output with appropriate formatting
System.out.println ("Subtotal: " + fmt1.format(subtotal));
System.out.println ("Tax: " + fmt1.format(tax) + " at "
+ fmt2.format(TAX_RATE));
System.out.println ("Total: " + fmt1.format(totalCost));
}
}
Copyright © 2012 Pearson Education, Inc.
Formatting Output
• The DecimalFormat class can be used to format a floating
point value in various ways
• The constructor of the DecimalFormat class takes a string
that represents a pattern for the formatted number, for
example,
DecimalFormat fmt = new DecimalFormat("0.###");
Indicates the fractional portion of the value should be rounded to three
digits
Formatting Output
• String format (double number)
– Returns a string containing the specified number
formatted according to the current pattern.
• For example, you can specify that the number
should be rounded to three decimal digits. For
example, 65.83752->65.838
//********************************************************************
// CircleStats.java
Author: Lewis/Loftus
//
// Demonstrates the formatting of decimal values using the
// DecimalFormat class.
//********************************************************************
import java.util.Scanner;
import java.text.DecimalFormat;
public class CircleStats
{
//----------------------------------------------------------------// Calculates the area and circumference of a circle given its
// radius.
//----------------------------------------------------------------public static void main (String[] args)
{
int radius;
double area, circumference;
Scanner scan = new Scanner (System.in);
continued
Copyright © 2012 Pearson Education, Inc.
continued
System.out.print ("Enter the circle's radius: ");
radius = scan.nextInt();
area = Math.PI * Math.pow(radius, 2);
circumference = 2 * Math.PI * radius;
// 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));
}
}
Copyright © 2012 Pearson Education, Inc.
Exercise
• Suppose we have read in a double value num
from the user. Write code statements that print the
result of raising num to the fourth power. Output the
results to 2 decimal places.
Flow of Control
• The order of statement execution is called the flow
of control
• Unless specified otherwise, the order of statement
execution through a method is linear: one
statement after another in sequence
5-48
The if Statement
• 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.
5-49
Logic of an if statement
condition
evaluated
true
false
statement
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
5-50
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
5-51
//********************************************************************
// 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
5-52
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.");
}
}
5-53
Exercise
• Write a conditional statement that assigns 10,000
to the variable bonus if the value of the variable
goodsSold is greater than 500,000 .
5-54
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");
else
System.out.println(“Not same”);
5-55
Readings and Assignments
• Reading: Chapter 2.5, 3.1-3.6, 3.8
• Lab Assignment: Java Lab 3
• Self-Assessment Exercises:
– Self-Review Questions Section
• SR2.34, 2.35, 3.6, 3.7, 3.21, 3.23, 3.28
– After Chapter Exercises
• EX2.11 g, h, i, j, k, l, m, 3.4, 3.11