Liang, Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 2 Primitive Data Types and...
-
Upload
edmund-goodwin -
Category
Documents
-
view
229 -
download
0
Transcript of Liang, Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 2 Primitive Data Types and...
Liang, Introduction to Java Programming,revised by Dai-kaiyu1
Chapter 2 Primitive Data Types and Operations
Chapter 1 Introduction to Computers, Programs, and Java
Chapter 2 Primitive Data Types and Operations
Chapter 3 Control Statements
Chapter 5 Arrays
Chapter 4 Methods
Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word
Prerequisites for Part I
事实不可扭曲,意见大可自由
—— C.P.Scott
Liang, Introduction to Java Programming,revised by Dai-kaiyu2
Objectives To write Java programs to perform simple calculations (§2.2). To use identifiers to name variables, constants, methods, and classes (§2.3). To use variables to store data (§2.4-2.5). To program with assignment statements and assignment expressions (§2.5). To use constants to store permanent data (§2.6). To declare Java primitive data types: byte, short, int, long, float, double, char, and
boolean (§2.7 – 2.10). To use Java operators to write expressions (§2.7 – 2.10). To know the rules governing operand evaluation order, operator precedence, and
operator associativity (§2.11 – 2.12). To represent a string using the String type. (§2.13) To obtain input using the JOptionPane input dialog boxes (§2.14). To obtain input from console (§2.16 Optional). To format output using JDK 1.5 printf (§2.17). To become familiar with Java documentation, programming style, and naming
conventions (§2.18). To distinguish syntax errors, runtime errors, and logic errors (§2.19). To debug logic errors (§2.20).
Liang, Introduction to Java Programming,revised by Dai-kaiyu3
Introducing Programming with an Example
Example 2.1 Computing the Area of a Circle
ComputeAreaComputeArea
RunRun
Program = Algorithm + Data structure
Liang, Introduction to Java Programming,revised by Dai-kaiyu4
Trace a Program Executionpublic class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; 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); }}
no valueradius
allocate memory for radius
Liang, Introduction to Java Programming,revised by Dai-kaiyu5
Trace a Program Executionpublic class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; 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); }}
no valueradius
memory
no valuearea
allocate memory for area
Liang, Introduction to Java Programming,revised by Dai-kaiyu6
Trace a Program Executionpublic class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; 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); }}
20radius
no valuearea
assign 20 to radius
Liang, Introduction to Java Programming,revised by Dai-kaiyu7
Trace a Program Executionpublic class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; 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); }}
20radius
memory
1256.636area
compute area and assign it to variable area
Liang, Introduction to Java Programming,revised by Dai-kaiyu8
Trace a Program Executionpublic class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; 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); }}
20radius
memory
1256.636area
print a message to the console
A string constant should not cross lines
Liang, Introduction to Java Programming,revised by Dai-kaiyu9
Identifiers 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.
An identifier can be of any length.
Are used for naming variables, constants, methods, classes, and packages
Liang, Introduction to Java Programming,revised by Dai-kaiyu10
Liang, Introduction to Java Programming,revised by Dai-kaiyu11
Memory ConceptsVariables
Every variable has a name, a type, a size and a value
Name corresponds to location in memory
When new value is placed into a variable, replaces (and destroys) previous value
Reading variables from memory does not change them
Liang, Introduction to Java Programming,revised by Dai-kaiyu12
2.6 Memory Concepts
Visual Representation Sum = 0; number1 = 1; number2 = 2;
Sum = number1 + number2; after execution of statement
sum 0
sum 3
number1
number2
1
2
number1
number2
1
2
Liang, Introduction to Java Programming,revised by Dai-kaiyu13
Variables
Used to store data in a program
// Compute the first arearadius = 1.0;area = radius * radius * 3.14159;System.out.println("The area is " + area + " for radius "+radius);
// Compute the second arearadius = 2.0;area = radius * radius * 3.14159;System.out.println("The area is “ + area + " for radius "+radius);
Liang, Introduction to Java Programming,revised by Dai-kaiyu14
Declaring Variables
Giving the name and the data type of variables
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;
Liang, Introduction to Java Programming,revised by Dai-kaiyu15
Java data types
Data type is the classification of forms of information
Data type is declared using keywords
Java is strongly typed
Liang, Introduction to Java Programming,revised by Dai-kaiyu16
Assignment Statements
Give a value to the declared variable
x = 1; // Assign 1 to x;
radius = 1.0; // Assign 1.0 to radius;
a = 'A'; // Assign 'A' to a;
Liang, Introduction to Java Programming,revised by Dai-kaiyu17
Assignment Expressions
Expression: a computation involving values, variables, and operators that evaluates to a value.
X = 5 * ( 3 / 2 ) + 3 * 2;
Assignment expressions:
i = j = k = 1;
Liang, Introduction to Java Programming,revised by Dai-kaiyu18
Declaring and Initializingin One Step
int x = 1;
double d = 1.4;
float f = 1.4;
Is this statement correct?
A variable in method must be assigned a value before it can be used
Liang, Introduction to Java Programming,revised by Dai-kaiyu19
Constants
final double PI = 3.14159;
final int SIZE = 3;
final datatype CONSTANTNAME = VALUE;
Liang, Introduction to Java Programming,revised by Dai-kaiyu20
Numerical Data Types
byte 8 bits
short 16 bits
int 32 bits
long 64 bits
float 32 bits
double 64 bits
type size range
byte 1byte -128 ~ 127
short 2bytes -215 ~ 215-1
int 4bytes -231 ~ 231-1
long 8bytes -263 ~ 263-1
Liang, Introduction to Java Programming,revised by Dai-kaiyu21
Operators
+, -, *, /, 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)
Liang, Introduction to Java Programming,revised by Dai-kaiyu22
Remainder Operatordetermine whether a number is even or odd using %.
Suppose you know January 1, 2005 is Saturday, you can find that the day for February 1, 2005 is Tuesday using the following expression:
Saturday is the 6th day in a week A week has 7 days
January has 31 days The 2nd day in a week is Tuesday
(6 + 31) % 7 is 2
Liang, Introduction to Java Programming,revised by Dai-kaiyu23
NOTE
Calculations involving floating-point numbers are approximated because these numbers are not stored with complete accuracy.
Integers are stored precisely. Therefore, calculations with integers yield a precise integer result.
Show case FloatIsNotPrecise.java
Liang, Introduction to Java Programming,revised by Dai-kaiyu24
Number Literals
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;
byte b = 1000 Wrong
A compilation error would occur if the literal were too large for the variable to hold.
Liang, Introduction to Java Programming,revised by Dai-kaiyu25
Number LiteralsAn 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.
long j = 10; Is this statement correct?
By default, a floating-point literal is treated as a double type 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.
Floating-point literals can also be specified in scientific notation, for example, 1.23456e+2
correct
Liang, Introduction to Java Programming,revised by Dai-kaiyu26
Arithmetic Expressions
)94
(9))(5(10
5
43
y
x
xx
cbayx
is translated to
(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)
Liang, Introduction to Java Programming,revised by Dai-kaiyu27
Shortcut Assignment Operators
Operator Example Equivalent
+= i+=8 i = i+8
-= f-=8.0 f = f-8.0
*= i*=8 i = i*8
/= i/=8 i = i/8
%= i%=8 i = i%8
Liang, Introduction to Java Programming,revised by Dai-kaiyu28
Increment andDecrement Operators
Operator Name Description++var preincrement The expression (++var)
increments var by 1 and evaluates to the new value in var after the
increment.var++ postincrement The expression (var++) evaluates
to the original value in var and increments var by 1.
--var predecrement The expression (--var) decrements var by 1 and evaluates
to the new value in var after the decrement.
var-- postdecrement The expression (var--) evaluates to the original value
in var and decrements var by 1.
Liang, Introduction to Java Programming,revised by Dai-kaiyu29
Increment andDecrement Operators, cont.
int i = 10; int newNum = 10 * i++;
int newNum = 10 * i; i = i + 1;
Same effect as
int i = 10; int newNum = 10 * (++i);
i = i + 1; int newNum = 10 * i;
Same effect as
Liang, Introduction to Java Programming,revised by Dai-kaiyu30
Assignment Expressions and Assignment Statements
Prior to Java 2, all the expressions can be used as statements. Since Java 2, only the following types of expressions can be statements:
variable op= expression; // Where op is +, -, *, /, or %
++variable;
variable++;
--variable;
variable--;
补充了解
Liang, Introduction to Java Programming,revised by Dai-kaiyu31
Numeric Type Conversion
Consider the following statements:
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
Liang, Introduction to Java Programming,revised by Dai-kaiyu32
Conversion Rules
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.
Liang, Introduction to Java Programming,revised by Dai-kaiyu33
Conversion Rules
Datatype of oprand1
Datatype of oprand2
After convertion
byte 、 short 、 char
int int
byte 、 short 、 char 、 int
long long
byte 、 short 、 char 、 int 、 long
float float
byte 、 short 、 char 、 int 、 long 、 float
double double
Liang, Introduction to Java Programming,revised by Dai-kaiyu34
Type Casting
Implicit casting double d = 3; (type widening)
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;
Liang, Introduction to Java Programming,revised by Dai-kaiyu35
Type Casting
For a variable of type int , explicit casting must be used
int i = 1;
byte b = i ;
For a literal of type integer, if in the persission range of short or byte. Explicit casting is not needed
byte i = 1;
wrong
Liang, Introduction to Java Programming,revised by Dai-kaiyu36
Character Data Type
char letter = 'A'; (ASCII)
char numChar = '4'; (ASCII)
char letter = '\u0041'; (Unicode)
char numChar = '\u0034'; (Unicode)
Four hexadecimal digits.
NOTE: The increment and decrement operators can also be used on char variables to get the next or preceding Unicode character. the following statements display character b.
char ch = 'a';
System.out.println(++ch);
Liang, Introduction to Java Programming,revised by Dai-kaiyu37
Unicode Format
Encoding: convert a character to its binary representation
Java characters use Unicode, a 16-bit encoding scheme
Unicode can represent 65,536 characters
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
Liang, Introduction to Java Programming,revised by Dai-kaiyu38
Escape Sequences for Special Characters
Description Escape Sequence Unicode
Backspace \b \u0008
Tab \t \u0009
Linefeed \n \u000A
Carriage return \r \u000D
Backslash \\ \u005C
Single Quote \' \u0027
Double Quote \" \u0022Show case Welcome4.java
Liang, Introduction to Java Programming,revised by Dai-kaiyu39
Appendix B: ASCII Character Set
ASCII is a 7-bits encoding scheme
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
Liang, Introduction to Java Programming,revised by Dai-kaiyu40
ASCII Character Set, cont.
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
Liang, Introduction to Java Programming,revised by Dai-kaiyu41
Casting between char and Numeric Types
int i = 'a'; // Same as int i = (int)'a';
char c = 97; // Same as char c = (char)97;
char letter = ‘A’;
System.out.println( letter+10);
System.out.println((char)(letter+10));
Integerchar :lower sixteen bits are used
Floating-pointchar :first cast into an int
Char numeric type : Unicode is used
Liang, Introduction to Java Programming,revised by Dai-kaiyu42
The boolean Type and Operators
six comparison operators (relational operators)
The result of the comparison is a Boolean value: true or false(can’t using 1 or 0). boolean b = (1 > 2);
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
Liang, Introduction to Java Programming,revised by Dai-kaiyu43
Boolean Operators
Operator Name
! not
&& and
|| or
^ exclusive or
Also called logic operators
Liang, Introduction to Java Programming,revised by Dai-kaiyu44
Truth Table for Operator !
p !p
true false
false true
Example
!(1 > 2) is true, because (1 > 2) is false.
!(1 > 0) is false, because (1 > 0) is true.
Liang, Introduction to Java Programming,revised by Dai-kaiyu45
Truth Table for Operator &&
p1 p2 p1 && p2
false false false
false true false
true false false
true true true
Example
(3 > 2) && (5 >= 5) is true, because (3 > 2) and (5 >= 5) are both true.
(3 > 2) && (5 > 5) is false, because (5 > 5) is false.
Liang, Introduction to Java Programming,revised by Dai-kaiyu46
Truth Table for Operator ||
p1 p2 p1 || p2
false false false
false true true
true false true
true true true
Example
(2 > 3) || (5 > 5) is false, because (2 > 3) and (5 > 5) are both false.
(3 > 2) || (5 > 5) is true, because (3 > 2) is true.
Liang, Introduction to Java Programming,revised by Dai-kaiyu47
Truth Table for Operator ^
p1 p2 p1 ^ p2
false false false
false true true
true false true
true true false
Example
(2 > 3) ^ (5 > 1) is true, because (2 > 3) is false and (5 > 1) is true.
(3 > 2) ^ (5 > 1) is false, because both (3 > 2) and (5 > 1) are true.
One of p1 and p2 is true, but not both
Liang, Introduction to Java Programming,revised by Dai-kaiyu48
Examples
System.out.println("Is " + num + " divisible by 2 and 3? " +
((num % 2 == 0) && (num % 3 == 0)));
System.out.println("Is " + num + " divisible by 2 or 3? " +
((num % 2 == 0) || (num % 3 == 0)));
System.out.println("Is " + num +
" divisible by 2 or 3, but not both? " +
((num % 2 == 0) ^ (num % 3 == 0)));
Liang, Introduction to Java Programming,revised by Dai-kaiyu49
Leap Year?
A year is a leap year if it is divisible by 4 but not by 100 or if it is divisible by 400.
boolean isLeapYear =
((year % 4 == 0) && (year % 100 != 0)) ||
(year % 400 == 0);
Liang, Introduction to Java Programming,revised by Dai-kaiyu50
The & and | Operators
&&: conditional AND operator (shortcut)&: unconditional AND operator||: conditional OR operator (shortcut)|: unconditional OR operator
exp1 && exp2(1 < x) && (x < 100)
(1 < x) & (x < 100)
Liang, Introduction to Java Programming,revised by Dai-kaiyu51
The & and | Operators
If x is 1, what is x after this expression?(x > 1) & (x++ < 10)
If x is 1, what is x after this expression?(1 > x) && ( 1 > x++)
How about (1 == x) | (10 > x++)?(1 == x) || (10 > x++)?
Liang, Introduction to Java Programming,revised by Dai-kaiyu52
Operator Precedence
How to evaluate 3 + 4 * 4 > 5 * (4 + 3) – 1?
The expression in the parentheses is evaluated first All binary operators except assignment operators are
left-associative. If operators with the same precedence are next to each
other, their associativity determines the order of evaluation. a – b + c – d is equivalent to ((a – b) + c) – d Assignment operators are right-associative. Therefore,
the expression a = b += c = 5 is equivalent to a = (b += (c = 5))
Liang, Introduction to Java Programming,revised by Dai-kaiyu53
Operator Precedence var++, var-- +, - (Unary plus and minus), ++var,--var (type) Casting ! (Not) *, /, % (Multiplication, division, and remainder) +, - (Binary addition and subtraction) <, <=, >, >= (Comparison) ==, !=; (Equality) & (Unconditional AND) ^ (Exclusive OR) | (Unconditional OR) && (Conditional AND) Short-circuit AND || (Conditional OR) Short-circuit OR =, +=, -=, *=, /=, %= (Assignment operator)
. Preceeds casting
Liang, Introduction to Java Programming,revised by Dai-kaiyu54
ExampleApplying the operator precedence and associativity rule, the expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is evaluated as follows:
3 + 4 * 4 > 5 * (4 + 3) - 1 3 + 4 * 4 > 5 * 7 – 1 3 + 16 > 5 * 7 – 1 3 + 16 > 35 – 1 19 > 35 – 1 19 > 34 false
(1) inside parentheses first
(2) multiplication
(3) multiplication
(4) addition
(5) subtraction
(6) greater than
Liang, Introduction to Java Programming,revised by Dai-kaiyu55
Operand Evaluation Order
Operands are evaluated from left to right in Java.
The left-hand operand of a binary operator is evaluated before any part of the right-hand operand is evaluated.
int a = 0;int x = ++a + a;
int a = 0;
int x = a + (++a); x becomes 1
x becomes 2
Liang, Introduction to Java Programming,revised by Dai-kaiyu56
Rule of Evaluating an Expression
· Rule 1: Evaluate whatever subexpressions you can possibly evaluate from left to right. · Rule 2: The operators are applied according to their precedence, as shown in Table 2.11.· Rule 3: The associativity rule applies for two operators next to each other with the same precedence.
Liang, Introduction to Java Programming,revised by Dai-kaiyu57
Rule of Evaluating an Expression
· Applying the rule, the expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is evaluated as follows:
3 + 4 * 4 > 5 * (4 + 3) - 1 3 + 16 > 5 * (4 + 3) - 1 19 > 5 * (4 + 3) - 1 19 > 5 * 7 - 1 19 > 35 – 1 19 > 34 false
(1) 4 * 4 is the first subexpression that can be evaluated from left.
(2) 3 + 16 is evaluated now.
(3) 4 + 3 is now the leftmost subexpression
that should be evaluated.
(4) 5 * 7 is evaluated now.
(5) 35 – 1 is evaluated now.
(6) 19 > 34 is evaluated now.
Liang, Introduction to Java Programming,revised by Dai-kaiyu58
The String Type represent a string of characters, use the data type called String. String message = "Welcome to Java"; String is actually a predefined class in the Java library 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.
Liang, Introduction to Java Programming,revised by Dai-kaiyu59
String Concatenation
// Three strings are concatenatedString message = "Welcome " + "to " + "Java"; // String Chapter is concatenated with number 2String s = "Chapter" + 2; // s becomes Chapter2 // String Supplement is concatenated with character BString s1 = "Supplement" + 'B'; // s becomes SupplementB
Liang, Introduction to Java Programming,revised by Dai-kaiyu60
String Concatenation
+ operator Addition String concatenation int y=5;
System.out.println("y+2="+y+2);
System.out.println(y+2+"y+2=");
System.out.println("y+2="+(y+2));
Show case Concatination.java
Liang, Introduction to Java Programming,revised by Dai-kaiyu61
Obtaining Input
Two common ways of obtaining input.
1. Using JOptionPane input dialogs (§2.14)
2. Using the JDK 1.5 Scanner class (Supplement T)
Liang, Introduction to Java Programming,revised by Dai-kaiyu62
Getting Input from Input Dialog Boxes
String string = JOptionPane.showInputDialog(
null, “Prompting Message”, “Dialog Title”,
JOptionPane.QUESTION_MESSAGE));
Liang, Introduction to Java Programming,revised by Dai-kaiyu63
Message dialog type Icon Description
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.
JOptionPane constants for message dialogs.
Liang, Introduction to Java Programming,revised by Dai-kaiyu64
Two Ways to Invoke the Method There are several ways to use the showInputDialog method. For 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.
JOptionPane. showInputDialog(x);
where x is a string for the prompting message.
Liang, Introduction to Java Programming,revised by Dai-kaiyu65
Converting Strings to Integers
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”.
Liang, Introduction to Java Programming,revised by Dai-kaiyu66
Converting Strings to Doubles
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”.
Liang, Introduction to Java Programming,revised by Dai-kaiyu67
Detailed case study: Adding Integers
Upcoming program Use input dialogs to input two values from user Use message dialog to display sum of the two values
Liang, Introduction to Java Programming,revised by Dai-kaiyu
68
1 // Fig. 2.9: Addition.java2 // An addition program.3 4 // Java extension packages5 import javax.swing.JOptionPane; // import class JOptionPane6 7 public class Addition {8 9 // main method begins execution of Java application10 public static void main( String args[] )11 {12 String firstNumber; // first string entered by user13 String secondNumber; // second string entered by user14 int number1; // first number to add15 int number2; // second number to add16 int sum; // sum of number1 and number217 18 // read in first number from user as a String19 firstNumber =20 JOptionPane.showInputDialog( "Enter first integer" );21 22 // read in second number from user as a String23 secondNumber =24 JOptionPane.showInputDialog( "Enter second integer" );25 26 // convert numbers from type String to type int27 number1 = Integer.parseInt( firstNumber ); 28 number2 = Integer.parseInt( secondNumber );29 30 // add the numbers31 sum = number1 + number2;32
Declare variables: name and data type.
Input first integer as a String, assign to firstNumber.
Add, place result in sum.
Convert strings to integers.
Liang, Introduction to Java Programming,revised by Dai-kaiyu
69
33 // display the results34 JOptionPane.showMessageDialog(35 null, "The sum is " + sum, "Results",36 JOptionPane.PLAIN_MESSAGE );37 38 System.exit( 0 ); // terminate application39 40 } // end method main41 42 } // end class Addition
Liang, Introduction to Java Programming,revised by Dai-kaiyu70
Detailed case study: Adding Integers
Location of JOptionPane for use in the program
Begins public class Addition Recall that file name must be Addition.java
Lines 10-11: main
Declaration firstNumber and secondNumber are variables
5 import javax.swing.JOptionPane;
7 public class Addition {
12 String firstNumber; // first string entered by user13 String secondNumber; // second string entered by user
Liang, Introduction to Java Programming,revised by Dai-kaiyu71
Detailed case study: Adding Integers
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 ;
• Can declare multiple variables of the same type at a time• Use comma separated list
Can add comments to describe purpose of variables
String firstNumber, secondNumber;
12 String firstNumber; // first string entered by user13 String secondNumber; // second string entered by user
Liang, Introduction to Java Programming,revised by Dai-kaiyu72
Good Practice
•meaningful varible name, self-documenting•String firstNumber;
•String secondNumber ;
•begin with lowercase letter
Liang, Introduction to Java Programming,revised by Dai-kaiyu73
Detailed case study: Adding Integers
Declares variables number1, number2, and sum of type int
int holds integer values : 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
• Single letter, single digit, single special character and escape sequences.
Primitive data types(Built in data types) • Boolean, char, byte, short, int, long, float, double
14 int number1; // first number to add15 int number2; // second number to add16 int sum; // sum of number1 and number2
Liang, Introduction to Java Programming,revised by Dai-kaiyu74
Detailed case study: Adding Integers
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 Argument appears as prompt text If wrong type of data entered (non-integer) or click Cancel,
error occurs (fault tolerant)
19 firstNumber =20 JOptionPane.showInputDialog( "Enter first integer" );
Liang, Introduction to Java Programming,revised by Dai-kaiyu75
Detailed case study: Adding Integers
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" )
19 firstNumber =20 JOptionPane.showInputDialog( "Enter first integer" );
Liang, Introduction to Java Programming,revised by Dai-kaiyu76
Detailed case study: Adding Integers
Similar to previous statement Assigns variable secondNumber to second integer input
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
23 secondNumber =24 JOptionPane.showInputDialog( "Enter second integer" );
27 number1 = Integer.parseInt( firstNumber ); 28 number2 = Integer.parseInt( secondNumber );
Liang, Introduction to Java Programming,revised by Dai-kaiyu77
Detailed case study: Adding Integers
Assignment statement Calculates sum of number1 and number2 (right hand
side) Uses assignment operator = to assign result to variable
sum Read as: sum gets the value of number1 + number2 number1 and number2 are operands
31 sum = number1 + number2;
Good Practice :
Space on either side of binary operator(make it stand out)
Liang, Introduction to Java Programming,revised by Dai-kaiyu78
Detailed case study: Adding Integers
Use showMessageDialog to display results "The sum is " + sum
Uses the operator + to "add" the string literal "The sum is" and sum
Concatenation of a String and another data type• Results in a new string• Automatic conversion of integer to string.
If sum contains 117, then "The sum is " + sum results in the new string "The sum is 117"
Note the space in "The sum is "
34 JOptionPane.showMessageDialog(35 null, "The sum is " + sum, "Results",36 JOptionPane.PLAIN_MESSAGE );
Liang, Introduction to Java Programming,revised by Dai-kaiyu79
Detailed case study: Adding Integers
Different version of showMessageDialog Requires four arguments (instead of two as before) First argument: null for now Second: string to display Third: string in title bar Fourth: type of message dialog with icon
• Line 36 no icon: JOptionPane.PLAIN_MESSAGE
34 JOptionPane.showMessageDialog(35 null, "The sum is " + sum, "Results",36 JOptionPane.PLAIN_MESSAGE );
Liang, Introduction to Java Programming,revised by Dai-kaiyu80
Example 2.2 Entering Input from Dialog Boxes
InputDialogDemoInputDialogDemo RunRun
This program first prompts the user to enter a year as an int value and checks if it is a leap year, it then prompts you to enter a double value and checks if it is positive.
A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400.
((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)
Liang, Introduction to Java Programming,revised by Dai-kaiyu81
Example 2.3 Computing Loan Payments
ComputeLoanComputeLoan RunRun
This program lets the user enter the interest rate, number of years, and loan amount and computes monthly payment and total payment.
12)1(11
numOfYearserestRatemonthlyInt
erestRatemonthlyIntloanAmount
Liang, Introduction to Java Programming,revised by Dai-kaiyu82
Example 2.4 Monetary Units
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.
ComputeChangeComputeChange RunRun
Liang, Introduction to Java Programming,revised by Dai-kaiyu83
Trace ComputeChange
int remainingAmount = (int)(amount * 100); // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // 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;
1156remainingAmount
remainingAmount initialized
Suppose amount is 11.56
Liang, Introduction to Java Programming,revised by Dai-kaiyu84
Trace ComputeChange
int remainingAmount = (int)(amount * 100); // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // 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;
1156remainingAmount
Suppose amount is 11.56
11numberOfOneDollars
numberOfOneDollars assigned
Liang, Introduction to Java Programming,revised by Dai-kaiyu85
Trace ComputeChange
int remainingAmount = (int)(amount * 100); // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // 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;
56remainingAmount
Suppose amount is 11.56
11numberOfOneDollars
remainingAmount updated
Liang, Introduction to Java Programming,revised by Dai-kaiyu86
Trace ComputeChange
int remainingAmount = (int)(amount * 100); // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // 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;
56remainingAmount
Suppose amount is 11.56
11numberOfOneDollars
2numberOfOneQuarters
numberOfOneQuarters assigned
Liang, Introduction to Java Programming,revised by Dai-kaiyu87
Trace ComputeChange
int remainingAmount = (int)(amount * 100); // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // 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;
6remainingAmount
Suppose amount is 11.56
11numberOfOneDollars
2numberOfQuarters
remainingAmount updated
Liang, Introduction to Java Programming,revised by Dai-kaiyu88
Example 2.5 Displaying Current Time
Write a program that displays current time in GMT in the format hour:minute:second such as 1: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.
ShowCurrentTimeShowCurrentTime RunRun
Liang, Introduction to Java Programming,revised by Dai-kaiyu89
Getting Input Using Scanner
1. Create a Scanner object
Scanner scanner = 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 scanner = new Scanner(System.in);double d = scanner.nextDouble();TestScannerTestScanner RunRun
Optional Supplement T
Liang, Introduction to Java Programming,revised by Dai-kaiyu90
Formatting Output
Use the new JDK 1.5 printf statement.
System.out.printf(format, item);
Where format is a string that may consist of substrings and format specifiers. A format specifier specifies how an item should be displayed. An item may be a numeric value, character, boolean value, or a string. Each specifier begins with a percent sign.
JDK 1.5Feature
Liang, Introduction to Java Programming,revised by Dai-kaiyu91
Frequently-Used Specifiers JDK 1.5Feature
Specifier Output Example
%b a boolean value true or false
%c a character 'a'
%d a decimal integer 200
%f a floating-point number 45.460000
%e a number in standard scientific notation 4.556000e+01
%s a string "Java is cool" int count = 5;
double amount = 45.56;
System.out.printf("count is %d and amount is %f", count, amount);
display count is 5 and amount is 45.560000
items
Table 2.13 for detailed usage examples
Liang, Introduction to Java Programming,revised by Dai-kaiyu92
Programming Style and Documentation
Appropriate CommentsNaming ConventionsProper Indentation and Spacing LinesBlock Styles
Coding conventions
Liang, Introduction to Java Programming,revised by Dai-kaiyu93
Appropriate Comments
Include a summary at the beginning of the program to explain what the program does, its key features, its supporting data structures, and any unique techniques it uses.
Include your name, class section, instructor, date, and a brief description at the beginning of the program.
Javadoc brief intro
Liang, Introduction to Java Programming,revised by Dai-kaiyu94
Naming Conventions
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.
Liang, Introduction to Java Programming,revised by Dai-kaiyu95
Naming Conventions, cont.
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
Liang, Introduction to Java Programming,revised by Dai-kaiyu96
Proper Indentation and Spacing
Indentation Indent two spaces.
Spacing Use blank line to separate segments of the code.
Liang, Introduction to Java Programming,revised by Dai-kaiyu97
Block Styles
Use end-of-line style for braces.
public class Test { public static void main(String[] args) { System.out.println("Block Styles"); } }
public class Test { public static void main(String[] args) {
System.out.println("Block Styles"); } }
End-of-line style
Next-line style
Liang, Introduction to Java Programming,revised by Dai-kaiyu98
Programming Errors
Syntax Errors Detected by the compiler
Runtime Errors Causes the program to abort
Logic Errors Produces incorrect result
Liang, Introduction to Java Programming,revised by Dai-kaiyu99
Syntax Errorspublic class ShowSyntaxErrors { public static void main(String[] args) { i = 30; System.out.println(i + 4); }}
Not declared
Liang, Introduction to Java Programming,revised by Dai-kaiyu100
Runtime Errors
public class ShowRuntimeErrors { public static void main(String[] args) { int i = 1 / 0; }}
Devided by zero
Liang, Introduction to Java Programming,revised by Dai-kaiyu101
Logic Errors
public class ShowLogicErrors {
// Determine if a number is between 1 and 100 inclusively
public static void main(String[] args) {
// Prompt the user to enter a number
String input = JOptionPane.showInputDialog(null,
"Please enter an integer:",
"ShowLogicErrors", JOptionPane.QUESTION_MESSAGE);
int number = Integer.parseInt(input);
// Display the result
System.out.println("The number is between 1 and 100, " +
"inclusively? " + ((1 > number) && (number < 100)));
System.exit(0);
}
}
Wrong expression
Liang, Introduction to Java Programming,revised by Dai-kaiyu102
Debugging
Logic errors are called bugs. The process of finding and correcting errors is called debugging.
Debugger is a program that facilitates debugging. You can use a debugger to
Execute a single statement at a time.Trace into or stepping over a method.Set breakpoints.Display variables.Display call stack.Modify variables.
Liang, Introduction to Java Programming,revised by Dai-kaiyu103
Debugging in JBuilder
The debugger utility is integrated in JBuilder. You can pinpoint bugs in your program with the help of the JBuilder debugger without leaving the IDE. The JBuilder debugger enables you to set breakpoints and execute programs line by line. As your program executes, you can watch the values stored in variables, observe which methods are being called, and know what events have occurred in the program.
JBuilder Optional
Liang, Introduction to Java Programming,revised by Dai-kaiyu104
Setting BreakpointsA breakpoint is a stop sign placed on a line of source code that tells the debugger to pause when this line is encountered. Using the breakpoint, you can quickly move over the sections you know work correctly and concentrate on the sections causing problems.
JBuilder Optional
Liang, Introduction to Java Programming,revised by Dai-kaiyu105
Setting Breakpoints, cont.Cutter area
Breakpoint
As you debug your program, you can set as many breakpoints as you want, and can remove breakpoints at any time during debugging. The project retains the breakpoints you have set when you exit the project. The breakpoints are restored when you reopen it.
JBuilder Optional
Liang, Introduction to Java Programming,revised by Dai-kaiyu106
Starting the debugger1. Set breakpoints.
2. Choose the program (e.g., ShowCurrentTime.java in the project pane, and right-click the mouse button to display the context menu. Click Debug Using Defaults in the context menu to start debugging.
JBuilder Optional
Liang, Introduction to Java Programming,revised by Dai-kaiyu107
Console View
Console view
Console view displays output and errors. You can also enter input from the console view.
JBuilder Optional
Liang, Introduction to Java Programming,revised by Dai-kaiyu108
Stack View
Call stacks
Stack view displays the methods and local variables in the call stack.
JBuilder Optional
Liang, Introduction to Java Programming,revised by Dai-kaiyu109
Watch View
Data watches
You can add variables to the watch view. Watch view displays the contents of the variables in the watch view.
JBuilder Optional
Liang, Introduction to Java Programming,revised by Dai-kaiyu110
Adding Variables to Watch View
There are several ways to add variables to the watch view. A simple way is to highlight the variable and then right-click the mouse to display the context menu. Choose Add Watch in the context menu to add the variable to the watch view.
JBuilder Optional
Liang, Introduction to Java Programming,revised by Dai-kaiyu111
Controlling Program Execution
The program pauses at the first breakpoint line encountered. This line, called the current execution point, is highlighted and has a green arrow to the left. The execution point marks the next line of source code to be executed by the debugger.
When the program pauses at the execution point, you can issue debugging commands to control the execution of the program. You also can inspect or modify the values of variables in the program.
When JBuilder is in the debugging mode, the Run menu contains the debugging commands. Most of the commands also appear in the toolbar under the message pane. The toolbar contains additional commands that are not in the Run menu. Here are the commands for controlling program execution:
JBuilder Optional
Liang, Introduction to Java Programming,revised by Dai-kaiyu112
Debugger Commands in the Toolbar
Reset program
Resume program
Pause program
Step over
Step into
Step out
JBuilder Optional
Liang, Introduction to Java Programming,revised by Dai-kaiyu113
Debugger Commands in the MenuJBuilder Optional
Liang, Introduction to Java Programming,revised by Dai-kaiyu114
Debugger Commands
Step Over executes a single statement. If the statement contains a call to a method, the entire method is executed without stepping through it.
Step Into executes a single statement or steps into a method.
Step Out executes all the statements in the current method and returns to its caller.
Run to Cursor runs the program, starting from the current execution point, and pauses and places the execution point on the line of code containing the cursor, or at a breakpoint.
Run to End of Method runs the program until it reaches the end of the current method or a breakpoint.
Resume Program continues the current debugging session or restarts one that has finished or been reset.
Reset Program ends the current program and releases it from memory. Use Reset to restart an application from the beginning, as when you make a change to the code and want to run again from the beginning, or if variables or data structures become corrupted with unwanted values. This command terminates debugging and returns to the normal editing session.
Show Execution Point positions the cursor at the execution point in the content pane.
JBuilder Optional
Liang, Introduction to Java Programming,revised by Dai-kaiyu115
Tracing Execution
You may trace the program line by line and see the contents of the variables in the stack view. This is most convenient.
JBuilder Optional