Chapter 2

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 96

1

Chapter 2
Elementary Programming
Motivations
2

 In the preceding chapter, you learned how to create,


compile, and run a Java program.
 Starting from this chapter, you will learn how to solve
practical problems programmatically.
 Through these problems, you will learn Java primitive
data types and related subjects, such as variables,
constants, data types, operators, expressions, and input
and output.
Objectives
 To write Java programs to perform simple computations (§2.2).

3 To obtain input from the console using the Scanner class (§2.3).
 To use identifiers to name variables, constants, methods, and
classes (§2.4).
 To use variables to store data (§§2.5–2.6).
 To program with assignment statements and assignment
expressions (§2.6).
 To use constants to store permanent data (§2.7).
 To name classes, methods, variables, and constants by following
their naming conventions (§2.8).
 To explore Java numeric primitive data types: byte, short, int,
long, float, and double (§2.9.1).
 To perform operations using operators +, -, *, /, and % (§2.9.2).
 To perform exponent operations using Math.pow(a, b) (§2.9.3).
Objectives Cont.
 To write integer literals, floating-point literals, and literals in
4
scientific notation (§2.10).
 To write and evaluate numeric expressions (§2.11).
 To obtain the current system time using
System.currentTimeMillis() (§2.12).
 To use augmented assignment operators (§2.13).
 To distinguish between postincrement and preincrement and
between postdecrement and predecrement (§2.14).
 To cast the value of one type to another type (§2.15).
 To describe the software development process and apply it to
develop the loan payment program (§2.16).
 To represent characters using the char type (§2.17).
 To represent a string using the String type (§2.18).
 To obtain input using the JOptionPane input dialog boxes (§2.19).
animation

Trace a Program Execution


5
allocate memory
public class ComputeArea {
for radius
/** Main method */
public static void main(String[] args) {
double radius; radius no value
double area;

// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius "
+ radius + " is " + area);
}
}
animation

Trace a Program Execution


6

public class ComputeArea { memory


/** Main method */
public static void main(String[] args) { radius no value
double radius; area no value
double area;

// Assign a radius
radius = 20; allocate memory
for area
// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
animation

Trace a Program Execution


7
public class ComputeArea {
/** Main method */ assign 20 to radius
public static void main(String[] args) {
double radius;
radius 20
double area;
area no value
// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius "
+
radius + " is " + area);
}
}
animation

Trace a Program Execution


8
public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
double radius; radius 20
double area;
area 1256.636
// Assign a radius
radius = 20;
compute area and assign
// Compute area it to variable area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius "
+
radius + " is " + area);
}
}
animation

Trace a Program Execution


9
public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
double radius; radius 20
double area;
area 1256.636
// Assign a radius
radius = 20;

// Compute area
print a message to the
console
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
Notes
10

 The plus sign (+) has two meanings: one for addition
and the other for concatenating (combining) strings.
 The plus sign (+) in lines 13–14 is called a string
concatenation operator. It combines two strings into
one.
Reading Input from the Console
11

• you can use the Scanner class to create an object to read input from
System.in, as follows:
1. Create a Scanner object
Scanner input = new Scanner(System.in);
2. Use the methods next(), nextByte(), nextShort(), nextInt(),
nextLong(), nextFloat(), nextDouble(), or nextBoolean() to
obtain to a string, byte, short, int, long, float, double, or
boolean value.
For example,
System.out.print("Enter a double value: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble();
Reading Input from the Console
12

Create a Scanner object


Scanner input = new Scanner(System.in);

System.out.print("Enter a double value: ");


Scanner input = new Scanner(System.in);
double d = input.nextDouble();
Reading Input from the Console
13
Identifiers
14

 Identifiers are the names that identify the elements such as


classes, methods, and variables in a program.
 An identifier is a sequence of characters that consist of
letters, digits, underscores (_), and dollar signs ($).
 An identifier must start with a letter, an underscore (_), or a
dollar sign ($). It cannot start with a digit.
 An identifier cannot be a reserved word. (See Appendix A, “Java
Keywords,” for a list of reserved words).
 An identifier cannot be true, false, or
null.
 An identifier can be of any length.
Variables
15

 Variables are used to represent values that may be changed


in the program.
Declaring Variables
16

 To use a variable, you declare it by telling the compiler


its name as well as what type of data it can store.
 The variable declaration tells the compiler to allocate
appropriate memory space for the variable based on its
data type.
 The syntax for declaring a variable is
datatype variableName;
Declaring Variables
17

 The syntax for declaring a variable is


datatype variableName;

int x; // Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable;
Assignment Statements
18

 An assignment statement designates a value for a variable. An


assignment statement can be used as an expression in Java.
 The syntax for assignment statements is as follows:
variable = expression;

x = 1; // Assign 1 to x;
radius = 1.0; // Assign 1.0 to radius;
a = 'A'; // Assign 'A' to a;
area = radius * radius * 3.14159; // Compute area
Declaring and Initializing in One Step
19

 Whenever possible, declare a variable and assign its initial


value in one step.
 This will make the program easy to read and avoid programming
errors.

 int x = 1;
 double d = 1.4;
Named Constants
20

 A named constant is an identifier that represents a permanent


value.

final datatype CONSTANTNAME = VALUE;

final double PI = 3.14159; // Declare a constant


final int SIZE = 3;
Naming Conventions
21

 Choose meaningful and descriptive names.


 Variables and method names:
 Use lowercase. If the name consists of several words,
concatenate all in one, use lowercase for the first word, and
capitalize the first letter of each subsequent word in the name.
For example, the variables radius and area, and the method
computeArea.
Naming Conventions, cont.
22

 Class names:
 Capitalize the first letter of each word in the name. For
example, the class name ComputeArea.

 Constants:
 Capitalize all letters in constants, and use underscores to
connect words. For example, the constant PI and
MAX_VALUE
Numerical Data Types
23

 Java uses four types for integers: byte, short, int, and long.
 Java uses two types for floating-point numbers: float and double.
Numeric Operators
24
Integer Division
25

 +, -, *, /, and %

 5 / 2 yields an integer 2.
 5.0 / 2 yields a double value 2.5

 5 % 2 yields 1 (the remainder of the division)


Remainder Operator
26
 Remainder is very useful in programming.
 For example, an even number % 2 is always 0 and an odd number
% 2 is always 1.
 So you can use this property to determine whether a number is
even or odd.
 Suppose today is Saturday and you and your friends are going to
meet in 10 days. What day is in 10 days? You can find that day is
Tuesday using the following expression:

Saturday is the 6th day in a week


A week has 7 days
(6 + 10) % 7 is 2
The 2nd day in a week is Tuesday
After 10 days
Problem: Displaying Time
27

Write a program that obtains minutes from seconds.


NOTE
28
 Calculations involving floating-point numbers are
approximated because these numbers are not stored with
complete accuracy.
 For example,
 System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);
displays 0.5000000000000001, not 0.5, and
 System.out.println(1.0 - 0.9);

displays 0.09999999999999998, not 0.1.


 Integers are stored precisely. Therefore, calculations
with integers yield a precise integer result.
Exponent Operations
29

 The Math.pow(a, b) method can be used to compute ab .


 The pow method is defined in the Math class in the Java API.
 For example
Exponent Operations
30

System.out.println(Math.pow(2, 3));
// Displays 8.0
System.out.println(Math.pow(4, 0.5));
// Displays 2.0
System.out.println(Math.pow(2.5, 2));
// Displays 6.25
System.out.println(Math.pow(2.5, -2));
// Displays 0.16
Number Literals
31

 A literal is a constant value that appears directly in


the program.
 For example, 34, 1,000,000, and 5.0 are literals in
the following statements:

int i = 34;
long x = 1000000;
double d = 5.0;
Integer Literals
32

 An integer literal can be assigned to an integer variable as long as it


can fit into the variable.
 A compilation error would occur if the literal were too large for the
variable to hold.
 For example, the statement byte b = 1000 would cause a compilation error,
because 1000 cannot be stored in a variable of the byte type.
(Note that the range for a byte value is from –128 to 127.)
 An integer literal is assumed to be of the int type, whose value is
between -231 (-2147483648) to 231–1 (2147483647). To denote an
integer literal of the long type, append it with the letter L or l.
 L is preferred because l (lowercase L) can easily be confused with
1 (the digit one).
Integer Literals
33

 System.out.println

 The decimal value 65535 for hexadecimal number FFFF.


 System.out.println(oxFFFF)
Floating-Point Literals
34
 Floating-point literals are written with a decimal point.
 By default, a floating-point literal is treated as a double type
value.
 For example, 5.0 is considered a double value, not a float value.
 You can make a number a float by appending the letter f or F, and
make a number a double by appending the letter d or D.
 For example, you can use 100.2f or 100.2F for a float number, and
100.2d or 100.2D for a double number.
Scientific Notation
35

 Floating-point literals can also be specified in


scientific notation,
 for example,
 1.23456e+2, same as 1.23456e2, is equivalent to
123.456,
 and 1.23456e-2 is equivalent to 0.0123456.
 E (or e) represents an exponent and it can be either
in lowercase or uppercase.
Arithmetic Expressions
36

• Java expressions are evaluated in the same way as arithmetic


expressions.

3  4 x 10( y  5)(a  b  c ) 4 9 x
  9(  )
5 x x y
is translated to

(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)


How to Evaluate an Expression
37

• Though Java has its own way to evaluate an expression behind


the scene, the result of a Java expression and its corresponding
arithmetic expression are the same. Therefore, you can safely
apply the arithmetic rule for evaluating a Java expression.

3 + 4 * 4 + 5 * (4 + 3) - 1
(1) inside parentheses first
3 + 4 * 4 + 5 * 7 – 1
(2) multiplication
3 + 16 + 5 * 7 – 1
(3) multiplication
3 + 16 + 35 – 1
(4) addition
19 + 35 – 1
(5) addition
54 - 1
(6) subtraction
53
Problem: Converting Temperatures
38

Write a program that converts a Fahrenheit degree to


Celsius using the formula:

celsius  ( 95 )( fahrenheit  32)

Note: you have to write


celsius = (5.0 / 9) * (fahrenheit – 32)
Problem: Converting Temperatures
39
Problem: Displaying Current Time
40

 Write a program that displays current time in GMT in the format


hour:minute:second such as 13:45:19.
 The currentTimeMillis method in the System class returns the
current time in milliseconds since the midnight, January 1, 1970
GMT.
 (1970 was the year when the Unix operating system was
formally introduced.) You can use this method to obtain the
current time, and then compute the current second, minute, and
hour as follows.
Problem: Displaying Current Time

41
Shortcut Assignment Operators
42

 count = count + 1;
 the preceding statement can be written as: count += 1;
 The += is called the addition assignment operator. Table 2.4
shows other augmented assignment operators.
Increment and Decrement Operators
43

 The increment (++) and decrement (– –) operators are for


incrementing and decrementing a variable by 1.
Increment and Decrement Operators, Cont.
44
Increment and Decrement Operators, cont.
45

 Using increment and decrement operators makes expressions


short, but it also makes them complex and difficult to read.
 Avoid using these operators in expressions that modify
multiple variables, or the same variable for multiple times
such as this: int k = ++i + i.
Numeric Type Conversion
46

Consider the following statements:

byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
Conversion Rules
47

 When performing a binary operation involving two


operands of different types, Java automatically converts
the operand based on the following rules:
 
1.    If one of the operands is double, the other is converted
into double.
2.    Otherwise, if one of the operands is float, the other is
converted into float.
3.    Otherwise, if one of the operands is long, the other is
converted into long.
4.    Otherwise, both operands are converted into int.
Type Casting
48

 You can always assign a value to a numeric variable whose type


supports a larger range of values; thus,
 for instance, you can assign a long value to a float variable.
 You cannot, however, assign a value to a variable of a type with a
smaller range unless you use type casting.
 Casting is an operation that converts a value of one data type into
a value of another data type.
 Casting a type with a small range to a type with a larger range is known
as widening a type.
 Casting a type with a large range to a type with a smaller range is
known as narrowing a type
 Java will automatically widen a type, but you must narrow a type
explicitly.
Type Casting
49
 Implicit casting
double d = 3; (type widening)
 The syntax for casting a type is to specify the target type in

parentheses, followed by the variable’s name or the value to be


cast
 Explicit casting

int i = (int)3.0; (type narrowing)


int i = (int)3.9; (Fraction part is
truncated)
What is wrong? int x = 5 / 2.0;
range increases

byte, short, int, long, float, double


Type Casting
50
Problem: Keeping Two Digits After Decimal
Points
51
 Write a program that displays the sales tax with two digits after
the decimal point.
Software Development Process
52

The software development life cycle is a multi-stage process that


includes

At any stage of the software development life


cycle, it may be necessary to go back to a previous
stage to correct errors or deal with other issues that
might prevent the software from functioning as
expected
Requirement Specification
53

A formal process that seeks to


Requirement
Specification understand the problem and
document in detail what the
System
Analysis software system needs to do. This
phase involves close interaction
System
Design between users and designers.

Implementation

Testing

Most of the examples in this book are simple,


and their requirements are clearly stated. In Deployment
the real world, however, problems are not
well defined. You need to study a problem Maintenance
carefully to identify its requirements.
System Analysis
54
Seeks to analyze the business
Requirement process in terms of data flow, and
Specification
to identify the system’s input and
System
Analysis
output.
System
Design

Implementation

Testing
Part of the analysis entails modeling
the system’s behavior. The model is Deployment

intended to capture the essential


elements of the system and to define Maintenance

services to the system.


System Design
55

The process of designing the


Requirement
Specification system’s components.
System
Analysis

System
Design

Implementation

Testing

This phase involves the use of many levels


of abstraction to decompose the problem into Deployment

manageable components, identify classes


and interfaces, and establish relationships Maintenance
among the classes and interfaces.
Implementation
56

The process of translating the


Requirement
Specification system design into programs.
System
Separate programs are written for
Analysis each component and put to work
System together.
Design

Implementation

Testing

This phase requires the use of a


Deployment
programming language like Java.
The implementation involves Maintenance
coding, testing, and debugging.
Testing
57

Ensures that the code meets the


Requirement
Specification requirements specification and
System
weeds out bugs.
Analysis

System
Design

Implementation

Testing

An independent team of software


Deployment
engineers not involved in the design
and implementation of the project Maintenance
usually conducts such testing.
Deployment
58

Requirement
Specification
Deployment makes the project
available for use.
System
Analysis

System
Design

Implementation

Testing

For a Java applet, this means Deployment


installing it on a Web server; for a
Java application, installing it on the Maintenance
client's computer.
Maintenance
59

Requirement
Maintenance is concerned with
Specification
changing and improving the
System product.
Analysis

System
Design

Implementation

Testing

A software product must continue to Deployment

perform and improve in a changing


environment. This requires periodic Maintenance

upgrades of the product to fix newly


discovered bugs and incorporate changes.
Problem: Computing Loan Payments
60

This program lets the user enter the interest


rate, number of years, and loan amount, and
computes monthly payment and total
payment.
loanAmount  monthlyInterestRate
monthlyPayment 
1 1
(1  monthlyInterestRate) numberOfYears12
Character Data Type
61

 A character data type represents a single character.


 char letter = 'A'; (ASCII) // assigns character A to the char variable letter
 char numChar = '4'; (ASCII) //assigns digit character 4 to the char variable
numChar.
 A string literal must be enclosed in quotation marks (" ").
 A character literal is a single character enclosed in single quotation
marks (' ').
 Java supports Unicode
 A 16-bit Unicode takes two bytes, preceded by \u, expressed in four
hexadecimal digits that run from \u0000 to \uFFFF
 char letter = 'A';
 char letter = '\u0041'; // Character A's Unicode is 0041
Character Data Type Cont.
62

NOTE: The increment and decrement operators can also be


used on char variables to get the next or preceding Unicode
character.
For example, the following statements display character b.

char ch = 'a';
System.out.println(++ch);

b
Unicode Format
63

Java characters use Unicode, a 16-bit encoding scheme


established by the Unicode Consortium to support the
interchange, processing, and display of written texts in the
world’s diverse languages. Unicode takes two bytes,
preceded by \u, expressed in four hexadecimal numbers
that run from '\u0000' to '\uFFFF'. So, Unicode can
represent 65535 + 1 characters.
α β γ
Unicode \u03b1 \u03b2 \u03b3 for three Greek
letters
Problem: Displaying Unicodes
64

Write a program that displays two Chinese characters


and three Greek letters.
Escape Sequences for Special Characters
65

 System.out.println("He said "Java is fun""); compiler error


 Java uses a special notation to represent special characters, as
shown in Table 2.6. This special notation, called an escape
character
 An escape character, consists of a backslash (\) followed by a
character or a character sequence. (\t , \u03b1)
 System.out.println("He said \"Java is fun\"");
 The output is
He said "Java is fun"
 Note that the symbols \ and " together represent one character.
Escape Sequences for Special Characters
66
Appendix B: ASCII Character Set
67

ASCII Character Set is a subset of the Unicode from \u0000 to \u007f

a =97
ASCII Character Set, cont.
68

ASCII Character Set is a subset of the Unicode from \u0000 to \u007f

A=\u0041
Casting between char and Numeric Types
69

• A char can be cast into any numeric type, and vice versa
int i = 'a'; // Same as int i = (int)'a';
char c = 97; // Same as char c = (char)97;
Casting Example Comments

char ch = (char)0XAB0041; // The lower 16 bits hex code 0041 is


integer to char System.out.println(ch); assigned to ch
// ch is character A
floating is first cast into an int then to
Floating to char char ch = (char)65.25; char
System.out.println(ch); // Decimal 65 is assigned to ch
// ch is character A
Casting between char and Numeric Types
70
Problem: Monetary Units
71

This program lets the user enter the amount in decimal


representing dollars and cents and output a report listing
the monetary equivalent in single dollars, quarters,
dimes, nickels, and pennies. Your program should report
maximum number of dollars, then the maximum number
of quarters, and so on, in this order.
72
Trace ComputeChange
Suppose amount is 11.56

73int remainingAmount = (int)(amount * 100);


remainingAmount 1156
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100; remainingAmount
remainingAmount = remainingAmount % 100; initialized
// Find the number of quarters in the remaining amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;

// Find the number of dimes in the remaining amount


int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;

// Find the number of nickels in the remaining amount


int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining amount


int numberOfPennies = remainingAmount;
animation
Trace ComputeChange
Suppose amount is 11.56
int
74 remainingAmount = (int)(amount * 100);
remainingAmount 1156
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100; numberOfOneDollars 11
remainingAmount = remainingAmount % 100;

// Find the number of quarters in the remaining amount numberOfOneDollars


int numberOfQuarters = remainingAmount / 25;
assigned
remainingAmount = remainingAmount % 25;

// Find the number of dimes in the remaining amount


int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;

// Find the number of nickels in the remaining amount


int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining amount


int numberOfPennies = remainingAmount;
animation Trace ComputeChange
Suppose amount is 11.56
75int remainingAmount = (int)(amount * 100);
remainingAmount 56
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100; numberOfOneDollars 11
remainingAmount = remainingAmount % 100;

// Find the number of quarters in the remaining amount


int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
remainingAmount
// Find the number of dimes in the remaining amount updated
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;

// Find the number of nickels in the remaining amount


int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining amount


int numberOfPennies = remainingAmount;
animation Trace ComputeChange
Suppose amount is 11.56
76int remainingAmount = (int)(amount * 100);
remainingAmount 56
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100; numberOfOneDollars 11
remainingAmount = remainingAmount % 100;

// Find the number of quarters in the remaining amount


int numberOfQuarters = remainingAmount / 25; numberOfOneQuarters 2
remainingAmount = remainingAmount % 25;

// Find the number of dimes in the remaining amount


int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10; numberOfOne
Quarters
// Find the number of nickels in the remaining amount
int numberOfNickels = remainingAmount / 5;
assigned
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining amount


int numberOfPennies = remainingAmount;
animation
Trace ComputeChange
Suppose amount is 11.56
77int remainingAmount = (int)(amount * 100);
remainingAmount 6
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100; numberOfOneDollars 11
remainingAmount = remainingAmount % 100;

// Find the number of quarters in the remaining amount


int numberOfQuarters = remainingAmount / 25; numberOfQuarters 2
remainingAmount = remainingAmount % 25;

// Find the number of dimes in the remaining amount


int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10; remainingAmount
// Find the number of nickels in the remaining amount updated
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining amount


int numberOfPennies = remainingAmount;
The String Type
78

 The char type only represents one character.


 To represent a string of characters, use the data type called String.
For example,  
 String message = "Welcome to Java";
  String is actually a predefined class in the Java library just like the
System class and JOptionPane class.
 The String type is not a primitive type. It is known as a reference
type.
 Any Java class can be used as a reference type for a variable.
 Reference data types will be thoroughly discussed in Chapter 8, “Objects and
Classes.” For the time being, you just need to know how to declare a String
variable, how to assign a string to the variable, and how to concatenate strings
String Concatenation
79

// Three strings are concatenated


String message = "Welcome " + "to " + "Java";
 
// String Chapter is concatenated with number 2
String s = "Chapter" + 2; // s becomes Chapter2
 
// String Supplement is concatenated with character B
String s1 = "Supplement" + 'B'; // s1 becomes SupplementB

The next() method reads a string that ends with a whitespace character
JOptionPane Input
80

This book provides two ways of obtaining input.

1. Using the Scanner class (console input)


2. Using JOptionPane input dialogs
Getting Input from Input Dialog Boxes
81

String input = JOptionPane.showInputDialog(


"Enter an input");

***For output use:


JOptionPane.showMessageDialog(null, x);
Getting Input from Input Dialog Boxes
82

String string = JOptionPane.showInputDialog(


null, “Prompting Message”, “Dialog Title”,
JOptionPane.QUESTION_MESSAGE);
Getting Input from Input Dialog Boxes Cont.
Me ssa g e d ia lo g typ e Ic o n De sc rip tio n

JOptionPane.ERROR_MESSAGE Displays a dialog that indicates an error


to the user.

JOptionPane.INFORMATION_MESSAGE Displays a dialog with an informational


message to the user. The user can simply
dismiss the dialog.

JOptionPane.WARNING_MESSAGE Displays a dialog that warns the user of a


potential problem.

JOptionPane.QUESTION_MESSAGE Displays a dialog that poses a question to


the user. This dialog normally requires a
response, such as clicking on a Yes or a
No button.

JOptionPane.PLAIN_MESSAGE no icon Displays a dialog that simply contains a


message, with no icon.
Fig . 2.12 JOptionPane c o n sta n ts fo r m e ssa g e d ia lo g s.

String string = JOptionPane.showInputDialog(null, “Prompting Message”, “Dialog


83
Title”, JOptionPane.QUESTION_MESSAGE);
Getting Input from Input Dialog Boxes
84
Two Ways to Invoke the Method
85

 There are several ways to use the showInputDialog method. For


the time being, you only need to know two ways to invoke it.
1. One is to use a statement as shown in the example:
String string = JOptionPane.showInputDialog(null, x,
y, JOptionPane.QUESTION_MESSAGE);
 where x is a string for the prompting message, and y is a string for the
title of the input dialog box.

2. The other is to use a statement like this:


JOptionPane.showInputDialog(x);
 where x is a string for the prompting message.
Converting Strings to Integers
86

 The input returned from the input dialog box is a string.


 If you enter a numeric value such as 123, it returns “123”.
 To obtain the input as a number, you have to convert a
string into a number.
 
To convert a string into an int value, you can use the static
parseInt method in the Integer class as follows:
 
int intValue = Integer.parseInt(intString);
 
where intString is a numeric string such as “123”.
Converting Strings to Doubles
87

 To convert a string into a double value, you can use the


static parseDouble method in the Double class as follows:
 
double doubleValue =Double.parseDouble(doubleString);
 
where doubleString is a numeric string such as “123.45”.
88
(Summary )
Another Java Application: Adding Integers
• Upcoming program
– Use input dialogs to input two values from user
– Use message dialog to display sum of the two values

 2002 Prentice Hall. All rights reserved.


89
1 // Fig. 2.9: Addition.java Outline
2 // An addition program.
3
4 // Java extension packages Addition.java
5 import javax.swing.JOptionPane; // import class JOptionPane
6
7 public class Addition {
8
Declare variables: name and data type.
Input first integer as a String, assign
9 // main method begins execution of Java application
10 to firstNumber.
public static void main( String args[] )
11 {
12 String firstNumber; // first string entered by user
13 String secondNumber; // second string entered by user
14 int number1; // first number to add
15 int number2; // second number to add 1. import
16 int sum; // sum of number1 and number2
17
18 // read in first number from user as a String
2. class Addition
19 firstNumber =
20 JOptionPane.showInputDialog( "Enter first integer" ); 2.1 Declare variables
21
22 // read in second number from user as a String
(name and data type)
23 secondNumber = Convert strings to integers.
24 JOptionPane.showInputDialog( "Enter second integer" ); 3.
25
26 Add,
// convert numbers from type String to place
type result
int in sum. showInputDialog
27 number1 = Integer.parseInt( firstNumber );
28 number2 = Integer.parseInt( secondNumber ); 4. parseInt
29
30 // add the numbers
31 sum = number1 + number2; 5. Add numbers, put
32 result in sum
 2002 Prentice Hall.
All rights reserved.
90
33 // display the results Outline
34 JOptionPane.showMessageDialog(
35 null, "The sum is " + sum, "Results",
36 JOptionPane.PLAIN_MESSAGE );
37
38 System.exit( 0 ); // terminate application
39
40 } // end method main
41
42 } // end class Addition
Program output

 2002 Prentice Hall.


All rights reserved.
91

Another Java Application: Adding Integers

5 import javax.swing.JOptionPane;

– Location of JOptionPane for use in the program


7 public class Addition {

– Begins public class Addition


• Recall that file name must be Addition.java
– Lines 10-11: main

12 String firstNumber; // first string entered by user


13 String secondNumber; // second string entered by user

– Declaration
• firstNumber and secondNumber are variables

 2002 Prentice Hall. All rights reserved.


92

Another Java Application: Adding Integers


12 String firstNumber; // first string entered by user
13 String secondNumber; // second string entered by user

– Variables
• Location in memory that stores a value
– Declare with name and data type before use
• firstNumber and secondNumber are of data type
String (package java.lang)
– Hold strings
• Variable name: any valid identifier
• Declarations end with semicolons ;
String firstNumber, secondNumber;

– Can declare multiple variables of the same type at a time


– Use comma separated list
– Can add comments to describe purpose of variables

 2002 Prentice Hall. All rights reserved.


93

Another Java Application: Adding Integers


14 int number1; // first number to add
15 int number2; // second number to add
16 int sum; // sum of number1 and number2

– Declares variables number1, number2, and sum of type


int
• int holds integer values (whole numbers): i.e., 0, -4, 97
• Data types float and double can hold decimal numbers
• Data type char can hold a single character: i.e., x, $, \n, 7

 2002 Prentice Hall. All rights reserved.


94

Another Java Application: Adding Integers


19 firstNumber =
20 JOptionPane.showInputDialog( "Enter first integer" );

– Reads String from the user, representing the first number


to be added
• Method JOptionPane.showInputDialog displays the
following:

• Message called a prompt - directs user to perform an action


• If wrong type of data entered (non-integer) or click Cancel,
error occurs

 2002 Prentice Hall. All rights reserved.


95

Another Java Application: Adding Integers


19 firstNumber =
20 JOptionPane.showInputDialog( "Enter first integer" );

– Result of call to showInputDialog given to


firstNumber using assignment operator =
• Assignment statement
• = binary operator - takes two operands
– Expression on right evaluated and assigned to variable on
left
• Read as: firstNumber gets value of
JOptionPane.showInputDialog( "Enter first
integer" )

 2002 Prentice Hall. All rights reserved.


96

Another Java Application: Adding Integers


23 secondNumber =
24 JOptionPane.showInputDialog( "Enter second integer" );

– Similar to previous statement


• Assigns variable secondNumber to second integer input

27 number1 = Integer.parseInt( firstNumber );


28 number2 = Integer.parseInt( secondNumber );

– Method Integer.parseInt
• Converts String argument into an integer (type int)
– Class Integer in java.lang
• Integer returned by Integer.parseInt is assigned to
variable number1 (line 27)
– Remember that number1 was declared as type int
• Line 28 similar

 2002 Prentice Hall. All rights reserved.

You might also like