Title: Manipulating Data Using Methods
1Chapter 3
- Manipulating Data Using Methods
2Introduction
- Data are collections of raw facts or figures
- A program performs operations oninput data to
output information - Input data can come from a variety of sources
- The program itself
- Users of the program
- External files
3The Body Mass Index Calculator
- An interactive program
- Accepts the weight and height from the user
- Calculates the BMI to gauge total body fat
- Displays the result
- Three versions
- Input/Output using the command prompt
- Input/Output using dialog boxes
- Web environments use an applet interface
4(a) console application in a command prompt window
(b) console application using dialog boxes
(c) applet
5 6Problem Analysis
- Convert user input to metric measurements
- Calculate the BMI
- Display the result
7Design the Solution
- Design the three kinds of user interfaces with
storyboards - Design the logic of the program
- Use pseudocode for sequential flow for all
programs - Use an event diagram for the applet
- Validate the design
- Compare the program design with the original
requirements
8pseudocode
event diagram
9Code the program
- Open TextPad and save as BodyMass.java
- Enter beginning comments (lines 1 9)/
Chapter 3 Body Mass Index Calculator
Programmer your name Date todays date
Filename BodyMass.java Purpose This project
calculates the body mass index based on a
person's height and weight./ - Line 10import java.io.
10Code the program
- Add class header and main method header(lines 12
15)public class BodyMass - public static void main(String args) throws
IOException -
11Code the program
- Import the java.io package
- Provides classes to support system input and
output - Add a throws IOException clause to the method
header - Warns the compiler that the possibility of input
or output errors exists - Gives the program the opportunity to handle input
or output errors during run-time without aborting
12Storing Data
- Java is a strongly typed language
- Variables must be declared with a data type
- Variable locations can hold only that data type
- Java has two categories of data types
- Primitive data types hold single data items
- Integers, characters, floating point, and
booleans are primitive types - Reference data types hold a value that refers to
the location of the data - All Objects and arrays are reference types
13 14Declaring Variables
15Code the program
- Declare and construct variables (lines16
19)// declare and construct variablesString
strHeight, strWeightint intInches,
intPoundsdouble dblKilograms, dblMeters,
dblIndex
16User Input Streams and the System Class
- The act of data flowing in and out of a program
is called a stream - The System class creates three streams when a
program executes
17User Input Streams and the System Class
- Data from input streams are first sent to a
buffer - The java.io package contains several stream
classes - InputStreamReader
- Decodes the bytes from the System.in buffer into
characters - BufferedReader
- Increases efficiency by temporarily storing the
input received from another class, such as
InputStreamReader - Aids in platform independence by simplifying the
process of reading text and numbers from various
input sources
18Using the BufferedReader class
- Call the BufferedReader constructor to
instantiate a BufferedReader object - The argument of the BufferedReader( ) method
instantiates an InputStreamReader - BufferedReader( ) returns a reference to the
input data from System.in - Line 20 BufferedReader dataIn new
BufferedReader (new InputStreamReader
(System.in))
19(No Transcript)
20User Prompts, Inputs, and Conversions
- The readLine() method reads a line of input text
and returns a String containing the line - The returned String must be explicitly converted
if the data is to be used as another data type - Each primitive data type has a wrapper class
allowing the primitive to be treated as an object - The wrapper classes provides a parse() method to
convert Strings to primitives, and vice versa
21Code the program
- Lines 22 - 30// print prompts and get input
- System.out.println("\tTHE SUN FITNESS CENTER
BODY MASS INDEX CALCULATOR") - System.out.println()
- System.out.print("\t\tEnter your height to the
nearest inch ") - strHeight dataIn.readLine()
- intInches Integer.parseInt(strHeight)
- System.out.print("\t\tEnter your weight to the
nearest pound ") - strWeight dataIn.readLine()
- intPounds Integer.parseInt(strWeight)
22Assignment Statements
- General syntax location value
23Arithmetic Operators
24Arithmetic Operators
- The order of operator precedence is a
predetermined order that defines the sequence in
which operators are evaluated in an expression - Addition, subtraction, multiplication, and
division can manipulate any numeric data type - When Java performs math on mixed data types, the
result is always the larger data type - Casts allow programmers to force a conversion
from one primitive type to another
25Comparison Operators
- A comparison operation results in a true or false
value that can be stored in a boolean variable
26Numeric Expressions
- Numeric expressions evaluate to a number
- Only numeric primitive data types may be used in
a numeric expression - A value and variable must be separated by an
arithmetic operator - Unless parentheses supercede, an expression is
evaluated left to right with the following rules
of precedence - Multiplication and/or division
- Integer division
- Modular division ( modulus)
- Addition and/or subtraction
27Conditional Expressions
- Conditional expression evaluate to either true or
false (10 lt 5 true) - Comparison operators, values, variables, methods,
and Strings may be used in a conditional
expression - Two operands must be separated by a comparison
operator - Unless parentheses supercede, an expression is
evaluated left to right with relational operators
(lt, lt, gt, gt) taking precedence over equality
operators (, !)
28Parentheses in Expressions
- Parentheses may be used to change the order of
operations - The part of the expression within the parentheses
is evaluated first - Parentheses can provide clarity in complex
expressions - Numeric and conditional expressions should be
grouped with parentheses - Parentheses can be nested
- Java evaluates the innermost expression first and
then moves on to the outermost expression
29Construction of Error-Free Expressions
- Java may not be able to evaluate a validly formed
expression due to the following logic errors - Dividing by zero
- Taking the square root of a negative value
- Raising a negative value to a non-integer value
- Using a value too great or too small for a given
data type - Comparing different data types in a conditional
expression
30The Math Class
31Using Variables in Output
32Code the program
- Lines 32 35
- // calculations
- dblMeters intInches / 39.36
- dblKilograms intPounds / 2.2
- dblIndex dblKilograms / Math.pow(dblMeters, 2)
33Code the program
- Lines 37 - 42
- // output
- System.out.println()
- System.out.println("\tYOUR BODY MASS INDEX
IS " Math.round(dblIndex) ".") - System.out.println()
-
34Compiling, Running, and Documenting the
Application
- Compile the Body Mass Index Calculator program
- Execute the program
- Test the program by entering the sample input
data supplied in the requirements phase at the
prompts - Verify the results
35Sample Results
36Using Swing Components
- Save the previous version of the Body Mass Index
Calculator with a new filename
BodyMassSwing.java - Use Search/Replace to find BodyMass and change
them all to BodyMassSwing in the program.
37Using Swing Components
- Remove the old import statement and replace with
import javax.swing.JOptionPane - Contains methods to create dialog boxes for
input, confirmation, and messages - Delete the IOException and BufferedReader code
- The swing dialog boxes buffer data from the user
and handle IO errors
38Code the program
- Lines 10 22
- import javax.swing.JOptionPane
- public class BodyMassSwing
-
- public static void main(String args)
-
- // declare and construct variables
- String strHeight, strWeight
- int intInches, intPounds
- double dblKilograms, dblMeters, dblIndex
- // print prompts and get input
- System.out.println("\tTHE SUN FITNESS CENTER
BODY MASS INDEX CALCULATOR")
39Swing Dialog Boxes
- Dialog boxes are created with the JOptionPane
show methods - The showInputDialog() and showConfirmDialog
return a String containing the user input - First argument null means to center in the
active window - Second argument is the display area inside the
dialog box - Third argument is the caption on the title bar
- Fourth argument is a constant refering to the
type of icon
40OptionPane.showMessageDialog(null, "message",
"caption", one of the arguments below)
JOptionPane.ERROR_MESSAGE
JOptionPane. INFORMATION_ MESSAGE
JOptionPane. WARNING_ MESSAGE
JOptionPane. QUESTION_ MESSAGE
JOptionPane. PLAIN_ MESSAGE
41Code the program
42Closing Programs that use Swing
- System.exit() terminates an application that
displays a GUI - The command prompt window closes when this method
is called - System.exit accepts an integer argument that
serves as a status code - 0 indicates successful termination
- 1 indicates abnormal termination
- Add Line 39 System.exit(0)
43Saving, Compiling, and Running the Swing Version
- Verify that the file name matches the class name
at the beginning of the code - Compile the source code
- Test with the same sample data for all versions
to compare output results - If incorrect or unrealistic data is entered by
the user, errors will occur - Errors and exception handling will be discussed
in a later chapter
44Run the application
45Moving to the Web
- The applet version of the Body Mass Index
Calculator has four kinds of objects - Image, Labels, TextFields, and Buttons
- Import three packages
- Java.applet
- Java.awt
- Java.awt.event
- Implement an ActionListener interface in the
class header - Informs the program to respond to user-driven
events
46Moving to the Web
- Every event class has one or more associated
listener interfaces
47Code the program
- Using TextPad, start a new program
- Save the program as BodyMassApplet.java
- Enter the first 13 lines
- /
- Chapter 3 Body Mass Index Calculator
- Programmer your name here
- Date todays date
- Filename BodyMassApplet.java
- Purpose This project calculates the body mass
index based - on a person's height and weight.
- /
- import java.applet.
- import java.awt.
- import java.awt.event.
48Code the program
- Lines 14 - 19
- public class BodyMassApplet extends Applet
implements ActionListener -
- // declare variables
- Image logo // declare an image object
- int intInches, intPounds
- double dblKilograms, dblMeters, dblIndex
49Adding Interface Components to an Applet
- Label
- Displays text in the applet window
- TextField
- Displays a text box for users to enter text
- Buttons
- Displays a command button for users to click
50Code the program
- Lines 21 - 28
- //construct components
- Label companyLabel new Label("THE SUN FITNESS
CENTER BODY MASS INDEX
CALCULATOR") - Label heightLabel new Label("Enter your height
to the nearest inch") - TextField heightField new TextField(10)
- Label weightField new Label("Enter you weight
to the nearest pound") - TextField weightField new TextField(10)
- Button calcButton new Button("Calculate")
- Label outputLabel new Label("Click the
Calculate Button to see your body mass
index.")
51The init() Method
- Initializes the window color and graphic
- Adds components to the applet window
- Registers the Buttons ActionListener
- Enter lines 30 42
52The actionPerformed() Method
- When a click event occurs, the ActionListeners
actionPerformed() method is triggered - Input values are retrieved with getText()
- Calculations are performed
- Output is sent to a label with setText()
- Enter lines 44 52
- public void actionPerformed(ActionEvent e)
-
- intInches Integer.parseInt(heightField.getText(
)) - intPounds Integer.parseInt(weightField.getText(
)) - dblMeters intInches / 39.36
- dblKilograms intPounds / 2.2
- dblIndex dblKilograms / Math.pow(dblMeters,
2) - outputLabel.setText("YOUR BODY MASS INDEX IS "
Math.round(dblIndex)
".")
53The paint() Method
- Draws the initialized image in the applet window
- Lines 54 - 58
54Creating an HTML Host Document for an Interactive
Applet
- Save and Compile the applet
- Fix any errors and compile again
- In TextPad create a new document and save as
BodyMassApplet.html - ltHTMLgt
- ltAPPLET CODE "BodyMassApplet.class" WIDTH
375 HEIGHT 300gt - lt/APPLETgt
- lt/HTMLgt
55Run the java applet
56File Management
- Coding and compiling an application creates
several files on your storage device - File naming conventions and the operating
systems capability of displaying icons can help
the programmer maintain a logical order - Three java files named after the program purpose
and user interface type - Three class files after compilation
- HTML host document
- Image file
57Chapter 3 Homework
- Short Answer, page 201
- 1 9, 11 - 15
- Only type the answers, not the questions
- All answers must be typed and printed out
- Debugging Assignment, page 205
- Programming Assignments
- Pages 208 - 215
- 3, 4, 6, 10