Download Class 1 ~ Chapter 1

Document related concepts

Name mangling wikipedia , lookup

Java (programming language) wikipedia , lookup

C syntax wikipedia , lookup

Go (programming language) wikipedia , lookup

C++ wikipedia , lookup

Multidimensional empirical mode decomposition wikipedia , lookup

K-nearest neighbors algorithm wikipedia , lookup

CAL Actor Language wikipedia , lookup

Java performance wikipedia , lookup

Java ConcurrentMap wikipedia , lookup

Corecursion wikipedia , lookup

C Sharp syntax wikipedia , lookup

C Sharp (programming language) wikipedia , lookup

Transcript
Class 6
1
Objectives
Identify, declare, and use primitive
data types
 Use the System class to create data
streams
 Use the Scanner class of functions to
handle user input

2
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

3
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

4
Variables
Variables are
like storage
locations in
the computer’s
memory.
5
Naming Rules of Variables

First character must be one of the letters
a-z, A-Z, or an underscore ( _ ) or a $

After first character use a-z, A-Z, 0-9,
underscore ( _ ) or $

Any length

Keep them meaningful
6
Variable Rules (con’t)

Case sensitive
– ItemsOrder does not equal
itemsorder

Cannot declare two variables of the
same name in a method

Cannot give a variable the same
name as a method
7
Intrinsic Data Types
JAVA has eight intrinsic data
types, which form the basis for all
other data types (i.e., classes):
1. boolean:
- a 1 byte value that is assigned
a value of either true or false
(both are JAVA defined values).
Boolean values have no direct
conversion to integer values,
and are initialized to false.
8
Intrinsic Data Types
2. byte:
- a 1 byte integer, capable of
representing numbers from
numbers from -128 to +127.
It is initialized to 0.
3. char:
- a 2 byte integer that is normally
used to represent character values
using the Unicode system (the
first 128 values of which
correspond to ASCII values).
It is initialized to \u0000.
9
Intrinsic Data Types
4. short:
- a 2 byte integer, able to represent
numbers between -32K and +32K.
It is initialized to 0.
5. int:
- a 4 byte integer, able to represent
numbers between -2 billion and
+2 billion.
It is initialized to 0.
10
Intrinsic Data Types
6. long:
- an 8 byte integer, capable of
representing numbers between
-2 63 and +2 63 .
It is initialized to 0.
7. float:
- a 4 byte IEEE format real number,
giving about 7 decimal digits
of precision.
It is initialized to 0.0f.
11
Intrinsic Data Types
8. double:
- an 8 byte IEEE format real number,
giving about 15 decimal digits
of precision.
It is initialized to 0.0d.
12
Key JAVA Operators
Operator
()
Description
Parenthesis
Example
(X+2)/3
13
Key JAVA Operators
Operator
*
Description
Multiply
Example
X*2
14
Key JAVA Operators
Operator
/
Description
Divide
Example
X/12
15
Key JAVA Operators
Operator
%
Description
Modulus
Example
7%3
16
Key JAVA Operators
Operator
+
Description
Add
Example
X+7
17
Key JAVA Operators
Operator
-
Description
Subtract
Example
X-6
18
Key JAVA Operators
Operator
>
Description
Greater than
Example
X>3
19
Key JAVA Operators
Operator
<
Description
Less than
Example
X<3
20
Key JAVA Operators
Operator
>=
Description
Greater than or equal
Example
X>=3
21
Key JAVA Operators
Operator
<=
Description
Less than or equal
Example
X<=3
22
Key JAVA Operators
Operator
==
Description
Equals
Example
X==3
23
Key JAVA Operators
Operator
!=
Description
Not equal
Example
X!=3
24
Key JAVA Operators
Operator
=
Description
Assignment operator
Example
Y=X+3
25
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
26
The Body Mass Index Calculator

Three versions
– Input/Output using the command
prompt
– Input/Output using dialog boxes
– Web environments use an applet
interface
27
(a) console application in a command prompt window
(b) console application using dialog boxes
(c) applet
28
29
Problem Analysis

Convert user input to metric
measurements
 Calculate the BMI
 Display the result
30
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

31
32
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 33

Coding the Program
34
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

35
36
Declaring Variables
37
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
38
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
39
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
40
41
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
42
Assignment Statements

General syntax: location = value
43
Arithmetic Operators
44
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
45
Comparison Operators

A comparison operation results in a true or false
value that can be stored in a boolean variable
46
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
47
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 (==, !=)
48
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
49
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 noninteger value
– Using a value too great or too small for
a given data type
– Comparing different data types in a
50
The Math Class
51
Using Variables in Output
52
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

53
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 54

Swing Dialog Boxes


Dialog boxes are created with the JOptionPane
“show” methods
The showInputDialog() and showConfirmDialog
return a String containing the user input
55
Swing Dialog Boxes
56
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

57
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
58
be discussed in a later chapter

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 userdriven events
59
Moving to the Web

Every event class has one or more
associated listener interfaces
60
Moving to the Web
61
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
62
The init() Method



Initializes the window color and graphic
Adds components to the applet window
Registers the Button’s ActionListener
63
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()
64
The paint() Method

Draws the initialized image in the applet window
65
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

66
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
67
Conclusion
of Class 4
68