This chapter discusses manipulating data using methods in Java programming. It covers declaring and using primitive data types, handling user input with the BufferedReader class and readLine() method, converting strings to numbers, and using arithmetic, comparison, and conditional operators in expressions. The chapter also demonstrates building three versions of a body mass index calculator program: a console application using command prompt input/output, a Swing application with dialog boxes, and an interactive applet. It describes initializing components, handling events, and file management for Java programs.
2. 2Chapter 3: Manipulating Data Using Methods
Chapter Objectives
⢠Identify, declare, and use primitive data
types
⢠Use the System class to create data
streams
⢠Instantiate the BufferedReader class in
code
⢠Use the readLine() method to handle user
input
3. 3Chapter 3: Manipulating Data Using Methods
Chapter Objectives
⢠Convert strings to numbers using the
parse() method
⢠Use assignment statements to store data
with proper identifiers
⢠Use operators and parentheses correctly
in numeric and conditional expressions
⢠Round an answer using the round()
method of the Math class
4. 4Chapter 3: Manipulating Data Using Methods
Chapter Objectives
⢠Use Swing components to build the GUI
for a Swing program
⢠Use the exit() method to close a Swing
program
⢠Implement an ActionListener to handle
events
⢠Add interface components to an applet
5. 5Chapter 3: Manipulating Data Using Methods
Chapter Objectives
⢠Use the init() and paint() methods to load
the applet interface
⢠Use the actionPerformed() method
⢠Run and test an interactive applet
⢠Manage Java source code files and Java
class files
6. 6Chapter 3: Manipulating Data Using Methods
Introduction
⢠Data are collections of raw facts or figures
⢠A program performs operations on input
data to output information
⢠Input data can come from a variety of
sources
â The program itself
â Users of the program
â External files
7. 7Chapter 3: Manipulating Data Using Methods
The 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
8. 8Chapter 3: Manipulating Data Using Methods
(b) console application using dialog boxes
(a) console application in a command prompt window
(c) applet
10. 10Chapter 3: Manipulating Data Using Methods
Problem Analysis
⢠Convert user input to metric measurements
⢠Calculate the BMI
⢠Display the result
11. 11Chapter 3: Manipulating Data Using Methods
Design 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
13. 13Chapter 3: Manipulating Data Using Methods
Coding 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
15. 15Chapter 3: Manipulating Data Using Methods
Storing 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
18. 18Chapter 3: Manipulating Data Using Methods
User 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
19. 19Chapter 3: Manipulating Data Using Methods
User 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
20. 20Chapter 3: Manipulating Data Using Methods
Using 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
22. 22Chapter 3: Manipulating Data Using Methods
User 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
â Example: height = dataIn.readLine();
inches = Integer.parseInt(height);
23. 23Chapter 3: Manipulating Data Using Methods
Assignment Statements
⢠General syntax: location = value
25. 25Chapter 3: Manipulating Data Using Methods
Arithmetic 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
26. 26Chapter 3: Manipulating Data Using Methods
Comparison Operators
⢠A comparison operation results in a true or false value
that can be stored in a boolean variable
27. 27Chapter 3: Manipulating Data Using Methods
Numeric 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
â Addition and/or subtraction
28. 28Chapter 3: Manipulating Data Using Methods
Conditional Expressions
⢠Conditional expression evaluate to either true or
false
⢠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 (<,
<=, >, >=) taking precedence over equality
operators (==, !=)
29. 29Chapter 3: Manipulating Data Using Methods
Parentheses 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
30. 30Chapter 3: Manipulating Data Using Methods
Construction 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
33. 33Chapter 3: Manipulating Data Using Methods
Compiling, 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
⢠Print the source code and screen images
for documentation
34. 34Chapter 3: Manipulating Data Using Methods
Using Swing Components
⢠Save the previous version of the Body
Mass Index Calculator with a new
filename
⢠Import the javax.swing.JOptionPane class
â 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
35. 35Chapter 3: Manipulating Data Using Methods
Swing Dialog Boxes
⢠Dialog boxes are created with the JOptionPane âshowâ
methods
⢠The showInputDialog() and showConfirmDialog return a
String containing the user input
37. 37Chapter 3: Manipulating Data Using Methods
Closing 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
38. 38Chapter 3: Manipulating Data Using Methods
Saving, 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
39. 39Chapter 3: Manipulating Data Using Methods
Moving 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
40. 40Chapter 3: Manipulating Data Using Methods
Moving to the Web
⢠Every event class has one or more associated
listener interfaces
42. 42Chapter 3: Manipulating Data Using Methods
Adding 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
43. 43Chapter 3: Manipulating Data Using Methods
The init() Method
⢠Initializes the window color and graphic
⢠Adds components to the applet window
⢠Registers the Buttonâs ActionListener
44. 44Chapter 3: Manipulating Data Using Methods
The actionPerformed() Method
⢠When a click event occurs, the ActionListenerâs
actionPerformed() method is triggered
â Input values are retrieved with getText()
â Calculations are performed
â Output is sent to a label with setText()
45. 45Chapter 3: Manipulating Data Using Methods
The paint() Method
⢠Draws the initialized image in the applet window
46. 46Chapter 3: Manipulating Data Using Methods
Creating an HTML Host Document
for an Interactive Applet
⢠Compile the applet
⢠Write an HTML Host Document to execute
the applet
â Use the <APPLET> tag to specify the
bytecode file, and width and height of the
window
⢠Use the same sample data to test the
applet
⢠Document the source code
47. 47Chapter 3: Manipulating Data Using Methods
File Management
⢠Coding and compiling an application creates
several files on your storage device
⢠File naming conventions and the operating
systemâs 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
48. 48Chapter 3: Manipulating Data Using Methods
Chapter Summary
⢠Identify, declare, and use primitive data
types
⢠Use the System class to create data
streams
⢠Instantiate the BufferedReader class in
code
⢠Use the readLine() method to handle user
input
49. 49Chapter 3: Manipulating Data Using Methods
Chapter Summary
⢠Convert strings to numbers using the
parse() method
⢠Use assignment statements to store data
with proper identifiers
⢠Use operators and parentheses correctly
in numeric and conditional expressions
⢠Round an answer using the round()
method of the Math class
50. 50Chapter 3: Manipulating Data Using Methods
Chapter Summary
⢠Use Swing components to build the GUI
for a Swing program
⢠Use the exit() method to close a Swing
program
⢠Implement an ActionListener to handle
events
⢠Add interface components to an applet
51. 51Chapter 3: Manipulating Data Using Methods
Chapter Summary
⢠Use the init() and paint() methods to load
the applet interface
⢠Use the actionPerformed() method
⢠Run and test an interactive applet
⢠Manage Java source code files and Java
class files