chapter 2 elementary programming -...

77
Chapter 2 Elementary Programming Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 1

Upload: others

Post on 14-Apr-2021

17 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Chapter 2 Elementary Programming

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 1

Page 2: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

MotivationsIn 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.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 2

Page 3: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

ObjectivesTo write Java programs to perform simple calculations (§2 2)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 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, and char (§§2.7 – 2.9).(§§ )To use Java operators to write numeric expressions (§§2.7–2.8).To represent characters using the char type (§2.9).To represent a string using the String type (§2.10).p g g g yp (§ )To obtain input from the console using the Scanner class (§§2.11-2.12).To become familiar with Java documentation, programming style, and naming conventions (§2.13).To distinguish syntax errors, runtime errors, and logic errors (§2.14).To debug logic errors (§2.15).(GUI) To obtain input using the JOptionPane input dialog boxes (§2.16).

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 3

Page 4: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Introducing Programming with an g g gExample

Listing 2.1 Computing the Area of a Circle

This program computes the area of the circle.

ComputeArea

R

IMPORTANT NOTE: To enable the buttons, you must download the entire slide file slide.zip and unzip the files into a directory (e.g., c:\slide) .

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 4

Run

Page 5: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Trace a Program Executionanimation

public class ComputeArea {/** Main method */public static void main(String[] args) {d bl di ldi

allocate memory for radius

double radius;double area;

// Assign a radius

no valueradius

gradius = 20;

// Compute areaarea radi s * radi s * 3 14159;area = radius * radius * 3.14159;

// Display resultsSystem.out.println("The area for the circle of radius " +radius + " is " + area);

}}

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 5

Page 6: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Trace a Program Executionanimation

public class ComputeArea {/** Main method */public static void main(String[] args) {d bl di no valueradius

memory

double radius;double area;

// Assign a radius

no valueradius

no valuearea

gradius = 20;

// Compute areaarea radi s * radi s * 3 14159;

allocate memory for area

area = radius * radius * 3.14159;

// Display resultsSystem.out.println("The area for the circle of radius " +radius + " is " + area);

}}

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 6

Page 7: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Trace a Program Executionanimation

public class ComputeArea {/** Main method */public static void main(String[] args) {d bl di 20radius

assign 20 to radius

double radius;double area;

// Assign a radius

20radius

no valuearea

gradius = 20;

// Compute areaarea radi s * radi s * 3 14159;area = radius * radius * 3.14159;

// Display resultsSystem.out.println("The area for the circle of radius " +radius + " is " + area);

}}

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 7

Page 8: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Trace a Program Executionanimation

public class ComputeArea {/** Main method */public static void main(String[] args) {d bl di 20radius

memory

double radius;double area;

// Assign a radius

20radius

1256.636area

gradius = 20;

// Compute areaarea radi s * radi s * 3 14159;

compute area and assign it to variable areaarea = radius * radius * 3.14159;

// Display resultsSystem.out.println("The area for the circle of radius " +radius + " is " + area);

}}

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 8

Page 9: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Trace a Program Executionanimation

public class ComputeArea {/** Main method */public static void main(String[] args) {d bl di 20radius

memory

double radius;double area;

// Assign a radius

20radius

1256.636area

gradius = 20;

// Compute areaarea radi s * radi s * 3 14159; i t t tharea = radius * radius * 3.14159;

// Display resultsSystem.out.println("The area for the circle of radius " +

print a message to the console

radius + " is " + area);}

}

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 9

Page 10: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

IdentifiersAn identifier is a sequence of characters that consist of letters, digits, underscores ( ), and dollar signs ($).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. g ( ) g– An identifier cannot be a reserved word. (See Appendix A,

“Java Keywords,” for a list of reserved words).

An identifier cannot be true, false, ornull.An identifier can be of any length.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 10

Page 11: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Variables// Compute the first arearadius = 1.0;area = radius * radius * 3.14159;System out println("The area is “ +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, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 11

area + for radius +radius);

Page 12: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Declaring Variablesgint x; // Declare x to be an

// i t i bl// integer variable;

double radius; // Declare radius to// b d bl i bl// be a double variable;

char a; // Declare a to be a// h t i bl// character variable;

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 12

Page 13: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Assignment Statementsgx = 1; // Assign 1 to x;

radius = 1.0; // Assign 1.0 to radius;

a = 'A'; // Assign 'A' to a;a A ; // Assign A to a;

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 13

Page 14: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Declaring and Initializingg gin One Step

int x = 1;

d bl d 1 4double d = 1.4;

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 14

Page 15: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Constantsfinal datatype CONSTANTNAME = VALUE;

final double PI = 3.14159; fi l i 3final int SIZE = 3;

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 15

Page 16: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Numerical Data Types Name Range Storage Size

byte –27 (-128) to 27–1 (127) 8-bit signed

short –215 (-32768) to 215–1 (32767) 16-bit signed

31 31 int –231 (-2147483648) to 231–1 (2147483647) 32-bit signed

long –263 to 263–1 64-bit signed (i.e., -9223372036854775808

to 9223372036854775807) to 9223372036854775807)

float Negative range: 32-bit IEEE 754 -3.4028235E+38 to -1.4E-45 Positive range: 1.4E-45 to 3.4028235E+38

double Negative range: 64-bit IEEE 754 -1.7976931348623157E+308 to -4.9E-324 Positive range:

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 16

4.9E-324 to 1.7976931348623157E+308

Page 17: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

TIP

A ll t t l t d t t hAn excellent tool to demonstrate how numbers are stored in a computer was d l d b Ri h d R l Ydeveloped by Richard Rasala. You can access it at

http://www.ccs.neu.edu/jpt/jpt_2_3/bitdisplay/applet.htm

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 17

Page 18: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Numeric Operators

Name Meaning Example Resultg p

+ Addition 34 + 1 35 - Subtraction 34.0 – 0.1 33.9 * Multiplication 300 * 30 9000 / Division 1.0 / 2.0 0.5 % Remainder 20 % 3 2

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 18

Page 19: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Integer Division

+, -, *, /, and %

5 / 2 ields an integer 25 / 2 yields an integer 2.

5.0 / 2 yields a double value 2.5

5 % 2 i ld 1 (th i d f th di i i )5 % 2 yields 1 (the remainder of the division)

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 19

Page 20: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Remainder OperatorRemainder is very useful in programming. For example, an even number % 2 is always 0 and an odd number % 2 is always 1 S thi t t d t i h th b1. 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 g g y ydays? You can find that day is Tuesday using the following expression:

Saturday is the 6th day in a week

A week has 7 days

After 10 days

The 2nd day in a week is Tuesday(6 + 10) % 7 is 2

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 20

Page 21: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Problem: Displaying TimeWrite a program that obtains hours and minutes from secondsminutes from seconds.

DisplayTime Run

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 21

Page 22: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

NOTECalculations involving floating-point numbers are approximated because these numbers are not storedapproximated because these numbers are not stored with complete accuracy. For example,

S t t i tl (1 0 0 1 0 1 0 1 0 1 0 1)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);

di l 0 09999999999999998 0 1 Idisplays 0.09999999999999998, not 0.1. Integers are stored precisely. Therefore, calculations with integers yield a precise integer result

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 22

yield a precise integer result.

Page 23: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Number LiteralsA literal is a constant value that appears directly i th F l 34 1 000 000 din 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;double d = 5.0;

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 23

Page 24: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Integer LiteralsAn integer literal can be assigned to an integer variable aslong as it can fit into the variable. A compilation error

ld if th lit l t l f th i bl twould occur if the literal were too large for the variable tohold. For example, the statement byte b = 1000 wouldcause a compilation error because 1000 cannot be storedcause a compilation error, because 1000 cannot be storedin a variable of the byte type.

An integer literal is assumed to be of the int type whoseAn integer literal is assumed to be of the int type, whosevalue is between -231 (-2147483648) to 231–1(2147483647). To denote an integer literal of the long(2147483647). To denote an integer literal of the longtype, append it with the letter L or l. L is preferred becausel (lowercase L) can easily be confused with 1 (the digit

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 24

one).

Page 25: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Floating-Point LiteralsFloating-point literals are written with a decimalpoint By default a floating point literal is treatedpoint. By default, a floating-point literal is treatedas a double type value. For example, 5.0 isconsidered a double value not a float value Youconsidered a double value, not a float value. Youcan make a number a float by appending the letter for F and make a number a double by appendingor F, and make a number a double by appendingthe letter d or D. For example, you can use 100.2for 100 2F for a float number and 100 2d or 100 2Dor 100.2F for a float number, and 100.2d or 100.2Dfor a double number.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 25

Page 26: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Scientific NotationFloating-point literals can also be specified inscientific notation, for example, 1.23456e+2,same as 1.23456e2, is equivalent to 123.456, and1 23456 2 i i l t t 0 0123456 E ( )1.23456e-2 is equivalent to 0.0123456. E (or e)represents an exponent and it can be either inlowercase or uppercaselowercase or uppercase.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 26

Page 27: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Arithmetic Expressionsp

)94(9))(5(1043 xcbayx +++−+ )(9))((5 yxx

y++−

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, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 27

Page 28: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

How to Evaluate an ExpressionpThough Java has its own way to evaluate an expression behind the scene the result of a Javaexpression behind the scene, the result of a Java expression and its corresponding arithmetic expression are the same Therefore you can safely apply theare the same. Therefore, you can safely apply the arithmetic rule for evaluating a Java expression.

3 + 4 * 4 + 5 * (4 + 3) - 1 3 + 4 * 4 + 5 * 7 – 1 3 + 16 + 5 * 7 – 1

(1) inside parentheses first

(2) multiplication

(3) l i li i3 + 16 + 35 – 1 19 + 35 – 1

54 1

(3) multiplication

(4) addition

(5) addition

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 28

54 - 1 53

(6) subtraction

Page 29: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Problem: Converting TemperaturesWrite a program that converts a Fahrenheit degree to Celsius using the formula:g

)32)(( 95 −= fahrenheitcelsius

FahrenheitToCelsius Run

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 29

Page 30: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Shortcut Assignment Operatorsg pOperator 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

%= i %= 8 i = i % 8

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 30

Page 31: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

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 valuevar++ 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 valuevar postdecrement The expression (var ) evaluates to the original value

in var and decrements var by 1.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 31

Page 32: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Increment andDecrement Operators, cont.

int i = 10; Same effect asint newNum = 10 * i++; int newNum = 10 * i;

i = i + 1;

Sa e e ect as

int i = 10; Same effect as int newNum = 10 * (++i); i = i + 1;

int newNum = 10 * i;

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 32

Page 33: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Increment andDecrement Operators, cont.

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.multiple times such as this: int k i i.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 33

Page 34: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Assignment Expressions and g pAssignment Statements

Prior to Java 2, all the expressions can be used as statements. Since Java 2, only the following types of

i b t t texpressions can be statements:variable op= expression; // Where op is +, -, *, /, or %++variable;variable++;--variable;variable--;

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 34

Page 35: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Numeric Type Conversionyp

Consider the following statements:

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

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 35

Page 36: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Conversion RulesWhen performing a binary operation involving two operands of different types, Java automaticallyoperands 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 Oth i if f th d i fl t th th i2. 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 is3. 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, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 36

p

Page 37: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Type CastingImplicit casting

double d = 3; (type widening)

Explicit castingint i = (int)3.0; (type narrowing)int i (int)3.0; (type narrowing)int i = (int)3.9; (Fraction part is truncated)

What is rong? int 5 / 2 0;What is wrong? int x = 5 / 2.0;

range increases

byte, short, int, long, float, double

range increases

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 37

Page 38: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Problem: Keeping Two Digits After p g gDecimal Points

Write a program that displays the sales tax with two digits after the decimal point.g p

SalesTax Run

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 38

Page 39: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Character Data Typechar letter = 'A'; (ASCII)h Ch '4' (ASCII)

Four hexadecimal digits.

char numChar = '4'; (ASCII)

char letter = '\u0041'; (Unicode)char numChar = '\u0034'; (Unicode)

NOTE: The increment and decrement operators can also be usedon char variables to get the next or preceding Unicode character.

l h f ll i di l h bFor example, the following statements display character b.char ch = 'a';S t t i tl (++ h)

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 39

System.out.println(++ch);

Page 40: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Unicode FormatJava 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 numberspreceded by \u, expressed in four hexadecimal numbers that run from '\u0000' to '\uFFFF'. So, Unicode can represent 65535 + 1 characters.represent 65535 1 characters.

Unicode \u03b1 \u03b2 \u03b3 for three Greek letters

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 40

Page 41: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Problem: Displaying UnicodesProblem: Displaying Unicodes

Write a program that displays two ChineseWrite a program that displays two Chinese characters and three Greek letters.

DisplayUnicode Run

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 41

Page 42: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Escape Sequences for Special CharactersDescription Escape Sequence Unicode

B k \b \ 0008Backspace \b \u0008

Tab \t \u0009

Linefeed \n \u000A

Carriage ret rn \ \ 000DCarriage return \r \u000D

Backslash \\ \u005C

Single Quote \' \u0027

Double Quote \" \u0022

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 42

Double Quote \" \u0022

Page 43: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Appendix B: ASCII Character SetASCII Character Set is a subset of the Unicode from \u0000 to \u007f

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 43

Page 44: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

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

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 44

Page 45: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Casting between char and N i TNumeric Types

i t i ' ' // S i t i (i t)' 'int i = 'a'; // Same as int i = (int)'a';

char c = 97; // Same as char c = (char)97;

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 45

Page 46: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

The String Type 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

i iti t It i k f t A J lprimitive 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 7, “Objects and Classes.” g y p , jFor the time being, you just need to know how to declare a Stringvariable, how to assign a string to the variable, and how to concatenate strings

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 46

concatenate strings.

Page 47: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

String Concatenation // Three strings are concatenatedString message = "Welcome " + "to " + "Java";g g ;

// String Chapter is concatenated with number 2String s = "Chapter" + 2; // s becomes Chapter2

// St i S l t i t t d ith h t B// String Supplement is concatenated with character BString s1 = "Supplement" + 'B'; // s becomes SupplementBSupplementB

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 47

Page 48: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Obtaining InputThis book provides two ways of obtaining input.

1. Using JOptionPane input dialogs (§2.11)2 Using the JDK 1 5 Scanner class (§2 16)2. Using the JDK 1.5 Scanner class (§2.16)

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 48

Page 49: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Getting Input Using Scanner1. Create a Scanner object

Scanner scanner = new Scanner(System.in);( y )

2. Use the methods next(), nextByte(), nextShort(), nextInt() nextLong() nextFloat() nextDouble()nextInt(), nextLong(), nextFloat(), nextDouble(), or nextBoolean() to obtain to a string, byte, short, int, long, float, double, or boolean value. For , g, , ,example,

System.out.print("Enter a double value: ");Scanner scanner = new Scanner(System.in);double d = scanner.nextDouble();

T S R

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 49

TestScanner Run

Page 50: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Problem:C ti L P tComputing Loan Payments

This program lets the user enter the interestThis program lets the user enter the interest rate, number of years, and loan amount and computes monthly payment and totalcomputes monthly payment and total payment.

11× erestRatemonthlyIntloanAmount

12)1(11 ×+

− arsnumberOfYeerestRatemonthlyInt

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 50

ComputeLoan Run

Page 51: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Problem: Monetary Unitsy

This program lets the user enter the amount inThis program lets the user enter the amount in decimal representing dollars and cents and output a report listing the monetary equivalent in singlea report listing the monetary equivalent in single dollars, quarters, dimes, nickels, and pennies. Your program should report maximum number ofYour program should report maximum number of dollars, then the maximum number of quarters, and so on in this orderand so on, in this order.

C Ch R

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 51

ComputeChange Run

Page 52: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Trace ComputeChangeSuppose amount is 11 56

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

// Find the number of one dollars

1156remainingAmount

Suppose amount is 11.56

int numberOfOneDollars = remainingAmount / 100;remainingAmount = remainingAmount % 100;

// Find the number of quarters in the remaining amount

remainingAmount initialized

q gint numberOfQuarters = remainingAmount / 25;remainingAmount = remainingAmount % 25;

// Find the number of dimes in the remaining amountint numberOfDimes = remainingAmount / 10;remainingAmount = remainingAmount % 10;

// Find the number of nickels in the remaining amountint numberOfNickels = remainingAmount / 5;remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining amount

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 52

int numberOfPennies = remainingAmount;

Page 53: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Trace ComputeChangeSuppose amount is 11 56

animation

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

// Find the number of one dollars

1156remainingAmount

Suppose amount is 11.56

11int numberOfOneDollars = remainingAmount / 100;remainingAmount = remainingAmount % 100;

// Find the number of quarters in the remaining amount

11numberOfOneDollars

numberOfOneDollars q gint numberOfQuarters = remainingAmount / 25;remainingAmount = remainingAmount % 25;

// Find the number of dimes in the remaining amount

assigned

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

// Find the number of nickels in the remaining amountint numberOfNickels = remainingAmount / 5;remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining amount

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 53

int numberOfPennies = remainingAmount;

Page 54: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Trace ComputeChangeSuppose amount is 11 56

animation

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

// Find the number of one dollars

56remainingAmount

Suppose amount is 11.56

11int numberOfOneDollars = remainingAmount / 100;remainingAmount = remainingAmount % 100;

// Find the number of quarters in the remaining amount

11numberOfOneDollars

q gint numberOfQuarters = remainingAmount / 25;remainingAmount = remainingAmount % 25;

// Find the number of dimes in the remaining amount

remainingAmount updated

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

// Find the number of nickels in the remaining amountint numberOfNickels = remainingAmount / 5;remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining amount

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 54

int numberOfPennies = remainingAmount;

Page 55: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Trace ComputeChangeSuppose amount is 11 56

animation

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

// Find the number of one dollars

56remainingAmount

Suppose amount is 11.56

11int numberOfOneDollars = remainingAmount / 100;remainingAmount = remainingAmount % 100;

// Find the number of quarters in the remaining amount

11numberOfOneDollars

q gint numberOfQuarters = remainingAmount / 25;remainingAmount = remainingAmount % 25;

// Find the number of dimes in the remaining amount

2numberOfOneQuarters

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

// Find the number of nickels in the remaining amount

Qassigned

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

// Find the number of pennies in the remaining amount

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 55

int numberOfPennies = remainingAmount;

Page 56: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Trace ComputeChangeSuppose amount is 11 56

animation

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

// Find the number of one dollars

6remainingAmount

Suppose amount is 11.56

11int numberOfOneDollars = remainingAmount / 100;remainingAmount = remainingAmount % 100;

// Find the number of quarters in the remaining amount

11numberOfOneDollars

q gint numberOfQuarters = remainingAmount / 25;remainingAmount = remainingAmount % 25;

// Find the number of dimes in the remaining amount

2numberOfQuarters

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

// Find the number of nickels in the remaining amount

remainingAmount updated

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

// Find the number of pennies in the remaining amount

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 56

int numberOfPennies = remainingAmount;

Page 57: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Problem: Displaying Current TimeWrite 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

b i h i d h hto obtain the current time, and then compute the current second, minute, and hour as follows.

ShowCurrentTime

R

Elapsed time

Unix Epoch Current Time

Time

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 57

RunUnix Epoch 01-01-1970 00:00:00 GMT System.CurrentTimeMills()

Page 58: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Programming Style and D t tiDocumentation

Appropriate CommentsAppropriate CommentsNaming ConventionsProper Indentation and SpacingLinesLinesBlock Styles

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 58

Page 59: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Appropriate Commentspp p

Include a summary at the beginning of theInclude a summary at the beginning of the program to explain what the program does, its key features, its supporting data structures, and any pp g yunique techniques it uses.

Include your name, class section, instructor, date, and a brief description at the beginning of the p g gprogram.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 59

Page 60: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Naming ConventionsgChoose 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 comp teAreathe method computeArea.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 60

Page 61: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Naming Conventions, cont.g ,Class names:

C it li th fi t l tt f h d i– Capitalize the first letter of each word in the name. For example, the class name ComputeArea.

Constants:Capitalize all letters in constants and use– Capitalize all letters in constants, and use underscores to connect words. For example, the constant PI and MAX VALUEMAX_VALUE

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 61

Page 62: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Proper Indentation and Spacingp p g

Indentation– Indent two spaces.

Spacing– Use blank line to separate segments of the code.Use blank line to separate segments of the code.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 62

Page 63: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Block StylesyUse end-of-line style for braces.

public class Test {

Next-line style {

public static void main(String[] args) { System.out.println("Block Styles"); }

style

}

public class Test {

End-of-line style

p public static void main(String[] args) {

System.out.println("Block Styles"); } }

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 63

Page 64: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Programming Errorsg gSyntax Errors– Detected by the compiler

Runtime Errors– Causes the program to abort

Logic ErrorsLogic Errors– Produces incorrect result

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 64

Page 65: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Syntax Errorspublic class ShowSyntaxErrors {public static void main(String[] args) {

i 30;i = 30;System.out.println(i + 4);

}}}

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 65

Page 66: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Runtime Errorspublic class ShowRuntimeErrors {public static void main(String[] args) {public static void main(String[] args) {int i = 1 / 0;

}}

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 66

Page 67: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Logic Errorspublic class ShowLogicErrors {public class ShowLogicErrors {// Determine if a number is between 1 and 100 inclusivelypublic static void main(String[] args) {

// Prompt the user to enter a numberpString input = JOptionPane.showInputDialog(null,

"Please enter an integer:","ShowLogicErrors", JOptionPane.QUESTION_MESSAGE);

int number = Integer.parseInt(input);

// Display the resultSystem out println("The number is between 1 and 100 " +System.out.println("The number is between 1 and 100, " +

"inclusively? " + ((1 < number) && (number < 100)));

System.exit(0);y}

}

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 67

Page 68: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

DebuggingLogic errors are called bugs. The process of finding and correcting errors is called debugging. A common approach to debugging is to use a combination of methods to narrow down to the part of the program where the bug is located. You can hand trace the program (i e catch errors byYou can hand-trace the program (i.e., catch errors by reading the program), or you can insert print statements in order to show the values of the variables or the executionorder to show the values of the variables or the execution flow of the program. This approach might work for a short, simple program. But for a large, complex program, the most effective approach for debugging is to use a debugger utility.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 68

Page 69: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

DebuggerDebugger is a program that facilitates debugging. You can use a debugger togg

Execute a single statement at a time.gTrace into or stepping over a method.Set breakpoints.pDisplay variables.Display call stack.p yModify variables.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 69

Page 70: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Getting Input from Input Dialog BoxesString input = JOptionPane.showInputDialog( "Enter an input");Enter an input );

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 70

Page 71: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Getting Input from Input Dialog BoxesString string = JOptionPane.showInputDialog(

null, “Prompting Message”, “Dialog Title”, , p g g , g ,JOptionPane.QUESTION_MESSAGE);

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 71

Page 72: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Two Ways to Invoke the MethodThere are several ways to use the showInputDialog method. For the time being, you only need to know two ways to invoke it.One is to use a statement as shown in the example: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 forwhere x is a string for the prompting message, and y is a string for the title of the input dialog box.

The other is to use a statement like this:JOptionPane.showInputDialog(x);

where x is a string for the prompting message

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 72

where x is a string for the prompting message.

Page 73: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Converting Strings to IntegersThe input returned from the input dialog box is a string. If you enter a numeric value such as 123, it returns “123”. y ,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:static parseInt method in the Integer class as follows:

int intValue = Integer parseInt(intString);int intValue = Integer.parseInt(intString);

where intString is a numeric string such as “123”Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All

rights reserved. 0136012671Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All

rights reserved. 0136012671 73

where intString is a numeric string such as 123 .

Page 74: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Converting Strings to DoublesTo convert a string into a double value, you can use the static parseDouble method in the Double class as follows:static parseDouble method in the Double class as follows:

double doubleValue =Double parseDouble(doubleString);double doubleValue =Double.parseDouble(doubleString);

h d bl St i i i t i h “123 45”where doubleString is a numeric string such as “123.45”.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 74

Page 75: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Problem: Computing Loan Payments Using Input Dialogs

S th di f ti lSame as the preceding program for computing loan payments, except that the input is entered from the i t di l d th t t i di l d iinput dialogs and the output is displayed in an output dialog.

11× erestRatemonthlyIntloanAmount

12)1(11 ×+

− arsnumberOfYeerestRatemonthlyInt

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 75

ComputeLoanUsingInputDialog Run

Page 76: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Debugging in NetBeansCompanion Website

Supplement II.E, Learning Java Effectively with NetBeans

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 76

Page 77: Chapter 2 Elementary Programming - Timlintimlin.net/csm/cis254/Chapter2.pdfObjectives)TowriteJavaprogramstoperformsimplecalculations(To write Java programs to perform simple calculations

Debugging in EclipseCompanion Website

Supplement II.G, Learning Java Effectively with NetBeans

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 77