chapter 1 - 1 chapter 3 numerical data. chapter 1 - 2 objectives understand numerical data type....

78
Chapter 1 - 1 Chapter 3 Numerical Data

Post on 21-Dec-2015

233 views

Category:

Documents


1 download

TRANSCRIPT

Chapter 1 - 1

Chapter 3

Numerical Data

Chapter 1 - 2

Objectives

•Understand numerical data type.•Write arithmetic expressions in Java.•Evaluate arithmetic expressions using the precedence rules.•Describe how the memory allocation works for objects and primitive data values.•Learn to use standard classes

– Math – for math expressions – GregorianCalendar - for manipulating date information such as

year, month, and day.– DecimalFormat - for formating numerical data– Integer, …,Long - Convert input string values to numerical data– System.in, System.out - Perform input and output.

Chapter 1 - 3

Java Data Types

Data Types supported by Java:• primitive types

– numeric types– integer type: byte, char, short, int, long– floating-point type: float, double– boolean

• reference types– class– interface– array

Notes:1. Instances of primitive types are values but not objects; only

instances of reference types are objects.

Chapter 1 - 4

Integer types

• namerepresentation range• byte 8-bit 2's complement -128~127• short16-bit 2's complement -32768~32767• int 32-bit 2's complement -2147483648 to

2147483647• long 64-bit 2's complement -263~263-1

(19 digits)• char 16-bit Unicode '\u0000' to '\uffff‘• or 0 ~ 65535

Chapter 1 - 5

floating-point and boolean types

• name representation range• float 32-bit, IEEE 754 1.40239846e-45 ~

3.40282347e+38• double 64-bit, IEEE 754 4.94065645841246544e-324• ~ 1.79769313486231570e+308Representation:• non-zero value: v = S x M x 2^E

– For float: S is +/- 1, M is a positive integer less than 2^24, and E is an integer in the inclusive range -149 to 104.

– For double: S is +/- 1, M is a positive integer less than 2^53, and E is an integer in the inclusive range -1045 to 1000.

• special values defined in IEEE 754:– +0, -0, +infinity, -Infinity, NaN.– note: 0/0.0 => NaN, – 1/0.0 => Infinity instead of overflow or divide by zero.

Chapter 1 - 6

IEEE 754 float-point single precision layout

• 0x7f800000 => positive infinity.

• 0xff800000 => negative infinity.

• 0x7f800001 ~ 0x7fffffff or 0xff800001~0xffffffff => NaN.

• Java use 0x7fc00000 as the canonical value of NaN.

• Distinct values of NaN are only accessible by use of the Float.floatToRawIntBits(float)

• In all other cases, let s, e, and m be three values that can be computed from the argument: – int s = ((bits >> 31) == 0) ? 1 : -1;

– int e = ((bits >> 23) & 0xff); // s bit is ignored by mask of 0xff

– int m = (e == 0) ? (bits & 0x7fffff) << 1 : (bits & 0x7fffff) | 0x800000;

– the floating-point result is s · m · 2 e-150.

Chapter 1 - 7

b31 b30 b29 b26b28 b27 b25 b16b17b18b19b21 b20b22b23b24

es(exponent)

b15 b14 b13 b10b12 b11 b9 b0b1b2b3b5 b4b6b7b8

m(man’tissa)

value is determined as follows:0. s = (b31 == 0 ? 1: -1);1. 255> e > 0 => value = s x (1.m)2 x 2 e –127 = s x (1m) x 2 e - 150

2. e = 0 => value = s x (b22.b21---b00)2 x 2 e-127 = s x (m 0)2 x 2 e - 127-23

3. e=255 && m == 0 => value = ( s == 0 ? Infinity : -Infinity)4. e = 255 && m != 0 => value = NaN; canonical NaN = 0181022

IEEE 754 float-point single precision layout

Chapter 1 - 8

Literals• A literal is the source code representation of a constant value of a

primitive type, or some specific object (of the type String, null, array or Class).

• Literal:

– IntegerLiteral : 123, 123l, 12400L

– FloatingPointLiteral: 123.4, 1.2e12, 12f, 12.3d

– BooleanLiteral: true, false

– CharacterLiteral: ‘a’, ‘\u123’, ‘\377’,…

– StringLiteral: “a book”,“tab\t and newline \n”

– NullLiteral: null

– ArrayLiteral: new int[]{1,2,3}.

– ClassLiteral: String.class

Chapter 1 - 9

Integer Literals

• An integer literal may be expressed in decimal (base 10), hexadecimal (base 16), or octal (base 8):

• It is of type int unless suffixed with ‘L’ or ‘l’.• IntegerLiteral:

– DecimalIntegerLiteral– HexIntegerLiteral – OctalIntegerLiteral

• DecimalIntegerLiteral:– 0– [1-9] [0-9]* [lL]? Ex: 123, 123l, 1243L

• HexIntegerLiteral:– 0 [xX] [0-9a-fA-F]+ [lL]? Ex: 0X1aB4, 0x23L, 0xffff

• OctalIntegerLiteral: – 0 [0-7]+[lL]? Ex: 000, 0377, 01177L

Chapter 1 - 10

Floating-Point Literals

• FloatingPointLiteral:– Digits . Digits? Exp? FloatType?– . Digits Exp? FloatType?– Digits Exp FloatType?– Digits Exp? FloatType

• Exp: [eE] [+ -]? Digits• FloatType: [fFdD]• Digits: [0-9]+• A FP literal is of type double unless it is suffixed with ‘F’ or ‘f’.• Ex:

– 12.34e12d, 1.23E-2, <= cf: 12.34e12d� � � � �– .11, .12E12f,– 12e-2, 1e12D <= cf: 0x1e12L– 33e2f, 33D

Space in the literalnot allowed

Chapter 1 - 11

Boolean Literals

• The boolean type has two values, represented by the literals true and false, formed from ASCII letters.

• A boolean literal is always of type boolean.• BooleanLiteral:

– true – false

Chapter 1 - 12

Character Literals

• expressed as a character or an escape sequence, enclosed in ASCII single quotes.

• A character literal is always of type char.• CharacterLiteral:

– ' SingleCharacter '– ' EscapeSequence '

• SingleCharacter:– Any Character but not any of ' \ CR LF

• ‘c‘ => compile-time error�• It is a compile-time error for a line terminator to appear

after the opening ' and before the closing '.

Chapter 1 - 13

Example:

• The following are examples of char literals: – 'a' '%' '\t' '\\' '\''– '\u03a9' '\uFFFF' '\177' '’ ‘‘

• Which of the following are correct literals:– ‘\u000a’, // this is LF– ‘\n’, // this is escape seq of LF– ‘\u000D’, // this is CR– ‘\r’

• Note: Characters written in unicode escape form ( \uxxxx ) will be converted to real chars before normal lexical analysis.

Chapter 1 - 14

String Literals• consists of zero or more characters enclosed in double

quotes. • Each character may be represented by an escape sequence.• always of type String• StringLiteral:

– " StringCharactersopt “ // empty string “” allowed• StringCharacters:

– StringCharacter– StringCharacters StringCharacter

• StringCharacter:– Any Character but not any of " \ CR LF– EscapeSequence

Chapter 1 - 15

Example:

• “a b c \u000d sd \u000a” // error!!• “This is a two-line

string“ //err! string can not across multilines• “ a b c \r sd \n” // OK• "" // the empty string• "\"" // a string containing " alone• "This is a string" // a string containing 16 chars• "This is a " + // actually a string-valued• “two-line strings” // constant expression, formed

// from two string literals

cf: we use octal literal 036 to represent int number 0x1e (= 30) but use ‘\36’ or ‘\036’ to represent char ‘\u001e’

Chapter 1 - 16

Escape Sequences for Character and String Literals

• Escape sequences allow for the representation of – some nongraphic characters, (TAB, LF, CR, …)– the single quote(‘), double quote(“), and backslash(\) characters

in character and string literals.• EscapeSequence:

– \b /* \u0008: backspace BS */– \t /* \u0009: horizontal tab HT */– \n /* \u000a: linefeed LF */– \f /* \u000c: form feed FF */– \r /* \u000d: carriage return CR */– \" /* \u0022: double quote " */– \' /* \u0027: single quote ' */– \\ /* \u005c: backslash \ */– OctalEscape /* \u0000 to \u00ff: from octal value */

Chapter 1 - 17

Octal Escape

• OctalEscape: // can represent only the first 256 chars– \ OctalDigit // [0-7] : \0 ~ \7– \ OctalDigit OctalDigit // [0-7][0-7]: \00 ~\77– \ ZeroToThree OctalDigit OctalDigit // [0-3][0-7][0-7]– // \000~\377

Chapter 1 - 18

The Null Literal and separators

• The null type has one value, the null reference, represented by the literal null, which is formed from ASCII characters.

• A null literal is always of the null type.• NullLiteral:

– null

Notes: Unlike C, in java 1. true ≠ 12. false ≠ 0 ≠ null

Chapter 1 - 19

Operators• The following 37 tokens are the operators, formed from

ASCII characters:• > < == <= >= != // relational• + - * / % // arithmetic• ! && || // conditional logical operations• ?: // ternary conditional operation• ++ -- // PRE/POST INCR/DECR• & | ^ ~ << >> >>> // Bit and boolean operation• = += -= *= /= &= |= // Assignments

^= %= <<= >>= >>>= – x *= y + z means x = x * (y + z) and the like.

Chapter 1 - 20

Manipulating Numbers

• In Java, to add two numbers x and y, we writex + y

• Before actual addition of the two numbers, we must declare their data type.

• If x and y are integer (variables), we writeint x, y;

orint x;int y;

Chapter 1 - 21

Variables

• When the declaration is made, memory space is allocated to store the values of x and y.– x and y are called variables.

• A variable has three properties:– A memory location to store the value,– The type of data stored in the memory location, and– The name used to refer to the memory location.

• Sample variable declarations:int x;int v, w, y;

Chapter 1 - 22

Numerical variables

• There are six numerical data types: byte, short, int, long, float, and double.

• Sample variable declarations:

int i, j, k; // default = 0 or no value

float numberOne, numberTwo;

long bigInteger;

double bigNumber;

• At the time a variable is declared, it also can be initialized. – int count = 10, height = 34;

Chapter 1 - 23

Data Type Precisions

The six data types differ in the precision of values they can store in memory.

Chapter 1 - 24

Assignment Statements

• We assign a value to a variable using an assignment statements.

• The syntax is

<variable> = <expression> ;• Examples:

sum = firstNumber + secondNumber;avg = (one + two + three) / 3.0;

Chapter 1 - 25

Arithmetic Operators

• The following table summarizes the arithmetic operators available in Java.

This is an integer division where the fractional part is truncated.

This is an integer division where the fractional part is truncated.

division:1. 10 / 3 = 3; -10 / 3 = -32. 10 / -3 = -3 ; -10 /-3 = 3.3. 10 / 0 Exception 10.0 /0 +Infinite

Chapter 1 - 26

Arithmetic Expression

• How does the expressionx + 3 * y

get evaluated? Answer: x is added to 3*y.• We determine the order of evaluation by following the

precedence rules. • A higher precedence operator is evaluated before the

lower one.– the same precedence, – evaluated left to right (left association) for most operators.– Ex: 5 - 3 -2 means (5 – 3 ) – 2 instead of 5 – ( 3 – 2).– right to left (right association) – Ex: 2 ^ 3 ^ 4 means 2^(3^4)

Chapter 1 - 27

Precedence Rules

Chapter 1 - 28

The Modulo Operator: a%b

• Used with integer types• Returns the remainder of the division of b by a• For example:

int a = 57; b = 16 ;

c = a%b;– c now has the value 9, the remainder of 57 divided by 16

• Integer / and % in java not the same as in normal arithmetic:• rules:

– x = y (x/y) + x % y --- always hold.

– x / y = sign(x/y) | x/ y| = x/y with fraction part removed;

– x%y = x – (x/y) *y = sign(x) (|x|%|y|) always holds

– ex: -10 / -3 = 3; -10 % -3 = -1; // -10 / 3 = ? ; -10 % 3 = ?

– ex: 10 / -3 = -3; 10 % -3 = 1;

Chapter 1 - 29

Type Casting

• If x is a float and y is an int, what will be the data type of the following expression?

x * y

The answer is float. • The above expression is called a mixed

expression. • promotion rules for mixed expressions:

– In a mixed expression, operand of low precision is automatically converted (casted; widen) into the high precision type before evaluation.

– ex: 3.2 + 4 promotes to– 3.2 + (double) 4 or 3.2 + 4d

Chapter 1 - 30

Type conversions• Java allows conversions between values of various numeric types.

– Except for boolean, values of all primitive types can be converted.

• Basic types of conversions:– Widening conversion: – int long; float double; char int; …

• always safe except for int float, double; longdouble.• automated performed by Java

– Narrowing conversion: long int; double float;…• must use the cast () operators; (except for int literal, which can be downcasted

to the required integral type automatically if it is inside the range of the left variable ).

• not always safe.

• Ex:– int i =13; byte b = i; // compiler error– short s = 134 ; // ok!! though 134 is int type , it is a literal.

Chapter 1 - 31

Use cast for narrowing conversion

• Ex:– int i = 13; – byte b = (byte) i; // force i to be converted to a byte– i = (int) 13.456 // force double literal 13.456 to int 13– i = (int) –12.6 // i == -12– i = Integer.MAX_VALUE // i = 2147483647– float j = i // need not cast, but data loss; j = 2.14748365E9– j == i ? true : false // will return true! why ?

• Math.round(), Math.floor(), Math.ceil() perform other types of conversion.

• short v.s. char:– short s = (short) 0xffff; // s = -1; 2’s comlement– char c = ‘\uffff’; // char behaves like unsigned short– int i1 = s; // i1 = -1– int i2 = c; // i2 = 65535

Chapter 1 - 32

Java Primitive Type Conversion rules

LR boolean

byte short char int long float double

boolean - N N N N N N N

byte Not allowed

- Y C Yes Y Y Y

short N Cast - C Y Y Y Y

char N C C - Y Y Y Y

int N C C C - Y Y* (loss)

Y

long N C C C C - Y* Y*

float N C C C C C - Y

double N C C C C C C -

Chapter 1 - 33

conversion rules

• precision order of numeric types– byte < (short ; char) < int < long < float < double– short and char are incomparable.– i.e.,– short s; char c;– s = c // error! must use (short) c.

• widening conversion– low precision high precision– automatcally done by javac; cast () not needed

• narrowing conversion– high precision low precision– must use cast ()

Chapter 1 - 34

Explicit Type Casting

• format:– ( <data type> ) <expression>

• Example

(float) x / 3

(int) (x / y * 3.0)

Type case x to float and then divide it by 3.

Type case x to float and then divide it by 3.

Type cast the result of the expression x / y * 3.0 to int.

Type cast the result of the expression x / y * 3.0 to int.

Chapter 1 - 35

Implicit Type Casting

• Consider the following expression:double x = 3 + 5;

• The result of 3 + 5 is of type int. However, since the variable x is double, the value 8 (type int) is promoted to 8.0 (type double) before being assigned to x.

• Notice that it is a promotion. Demotion is not allowed.

int x = 3.5;A higher precision value cannot be assigned to a lower precision variable.

A higher precision value cannot be assigned to a lower precision variable.

Chapter 1 - 36

Constants

• We can change the value of a variable. If we want the value to remain the same, we use a constant.

final double PI = 3.14159;final int MONTH_IN_YEAR = 12;final short FARADAY_CONSTANT = 23060;

These are constants, also called named constant.

These are constants, also called named constant.

The reserved word final is used to declare constants.

The reserved word final is used to declare constants.

These are called literal constant.

These are called literal constant.

Chapter 1 - 37

Primitive vs. Reference

• Numerical data are called primitive data types.• Objects are called reference data types, because

the contents are addresses that refer to memory locations where the objects are actually stored.

Chapter 1 - 38

Primitive Data Declaration and Assignments

Code State of Memory

int firstNumber, secondNumber;firstNumber = 234;secondNumber = 87;

AA

BB

firstNumber

secondNumber

A. A. Variables are allocated in memory.

A. A. Variables are allocated in memory.

B. B. Values are assigned to variables.

B. B. Values are assigned to variables.

234

87

Chapter 1 - 39

Assigning Numerical Data

Code State of Memory

number

A. A. The variable is allocated in memory.

A. A. The variable is allocated in memory.

B. B. The value 237237 is assigned to numbernumber.

B. B. The value 237237 is assigned to numbernumber.

237

int number;int number;

number = 237;number = 237;

AABB

CCnumber = 35;number = 35;

C. C. The value 3535 overwrites the

previous value 237.237.

C. C. The value 3535 overwrites the

previous value 237.237.

35

Chapter 1 - 40

Assigning Objects

Code State of Memory

customer

A. A. The variable is allocated in memory.

A. A. The variable is allocated in memory.Customer customer;Customer customer;

customer = new Customer( );customer = new Customer( );

customer = new Customer( );customer = new Customer( );

AA

BB

CC

B. B. The reference to the new object is assigned to customercustomer.

B. B. The reference to the new object is assigned to customercustomer.

CustomerCustomer

C. C. The reference to another object overwrites the reference in customer.customer.

C. C. The reference to another object overwrites the reference in customer.customer.

CustomerCustomer

Chapter 1 - 41

Having Two References to a Single Object

Code State of Memory

Customer clemens, twain,Customer clemens, twain,

clemens = new Customer( );clemens = new Customer( );

twain = clemens;twain = clemens;

AA

BB

CC

A. A. Variables are allocated in memory.

A. A. Variables are allocated in memory.

clemens

twain

B. B. The reference to the new object is assigned to clemensclemens.

B. B. The reference to the new object is assigned to clemensclemens.

CustomerCustomer

C. C. The reference in clemensclemens is assigned to

customer.customer.

C. C. The reference in clemensclemens is assigned to

customer.customer.

Chapter 1 - 42

Type Mismatch

• Suppose we want to input an age. Will this work?

int age;

age = JOptionPane.showInputDialog(null, “Enter your age”);

• No. String value cannot be assigned directly to an int variable.

Chapter 1 - 43

Type Conversion

• Wrapper classes are used to perform necessary type conversions, such as converting a String object to a numerical value.

int age;String inputStr;

inputStr = JOptionPane.showInputDialog(null, “Enter your age”);

age = Integer.parseInt(inputStr);

Chapter 1 - 44

Other Conversion Methods

Chapter 1 - 45

Sample Code Fragment

//code fragment to input radius and output//area and circumferencedouble radius, area, circumference;

String radiusStr = JOptionPane.showInputDialog(null, "Enter radius: " );

radius = Double.parseDouble(radiusStr);

//compute area and circumferencearea = PI * radius * radius;circumference = 2.0 * PI * radius;

JOptionPane.showMessageDialog(null, "Given Radius: " + radius + "\n" + "Area: " + area + "\n" +

"Circumference: " + circumference);

Chapter 1 - 46

Overloaded Operator +

• The plus operator + can mean two different operations, depending on the context.

• <val1> + <val2> is an addition if both are numbers. If either one of them is a String, the it is a concatenation.

• Evaluation goes from left to right.

output = “test” + 1 + 2; output = 1 + 2 + “test”;

Chapter 1 - 47

The DecimalFormat Class

• Use a DecimalFormat object to format the numerical output.

double num = 123.45789345;

DecimalFormat df = new DecimalFormat(“0.000”);//three decimal places

System.out.print(num);

System.out.print(df.format(num));

123.45789345

123.458

Chapter 1 - 48

3.5 Standard Output

• The showMessageDialog method is intended for displaying short one-line messages, not for a general-purpose output mechanism.

• Using System.out, we can output multiple lines of text to the standard output window.

Chapter 1 - 49

Standard Output Window

• A sample standard output window for displaying multiple lines of text.

• The exact style of standard output window depends on the Java tool you use.

Chapter 1 - 50

The print Method

• We use the print method to output a value to the standard output window.

• The print method will continue printing from the end of the currently displayed output.

• Example

System.out.print( “Hello, Dr. Caffeine.” );

Chapter 1 - 51

The println Method

• We use println instead of print to skip a line.

int x = 123, y = x + x;System.out.println( "Hello, Dr. Caffeine.“ );System.out.print( " x = “ );System.out.println( x );System.out.print( " x + x = “ );System.out.println( y );System.out.println( " THE END“ );

Chapter 1 - 52

Static imports

• static importimport static java.lang.System.out ; // import static java.lang.System.*;

// All static fields & methods in System are // imported!!

int x = 123, y = x + x;System.out.println( "Hello, Dr. Caffeine.“ );out.print( " x = “ );out.println( x );out.print( " x + x = “ );out.println( y );out.println( " THE END“ );

Chapter 1 - 53

Standard Input

• The technique of using System.in to input data is called standard input.– We can only input a single byte using System.in directly.– int in = System.in.read() ; // read a byte from System.in

• To input primitive data values, we use the Scanner class (from Java 5.0).

Scanner scanner;

scanner = new Scanner(System.in);

int num = scanner.nextInt();

Chapter 1 - 54

Method Example

nextByte( ) byte b = scanner.nextByte( );nextDouble( )double d = scanner.nextDouble( );nextFloat( ) float f = scanner.nextFloat( );nextInt( ) int i = scanner.nextInt( );nextLong( ) long l = scanner.nextLong( );nextShort( ) short s = scanner.nextShort( );next() String str = scanner.next();

Common Scanner Methods:

Chapter 1 - 55

The Math class

• The Math class in the java.lang package contains class methods for commonly used mathematical functions.

double num, x, y;

x = …;y = …;

num = Math.sqrt(Math.max(x,y)+12.4);

Chapter 1 - 56

Some Math Class Methods

Method Description

exp(a) Natural number e raised to the power of a.

log(a) Natural logarithm (base e) of a.

floor(a) The largest whole number less than or equal to a.

max(a,b) The larger of a and b.

pow(a,b) The number a raised to the power of b.

sqrt(a) The square root of a.

sin(a) The sine of a. (Note: all trigonometric functions are computed in radians)

Table 3.8 page 113 in the textbook contains a list of class methods defined in the Math class.

Computing the Height of a Pole

alphaRad = Math.toRadians(alpha); betaRad = Math.toRadians(beta);

height = ( distance * Math.sin(alphaRad) * Math.sin(betaRad) ) / Math.sqrt( Math.sin(alphaRad + betaRad) * Math.sin(alphaRad - betaRad) );

Chapter 1 - 58

Import static

import static java.lang.Math.*;// then all “Math” name can be skipped! alphaRad = toRadians(alpha); betaRad = toRadians(beta);

height =(distance*sin(alphaRad)*sin(betaRad)) / sqrt(sin(alphaRad+betaRad) * sin(alphaRad-betaRad));

Chapter 1 - 59

The GregorianCalendar Class

• Use a GregorianCalendar object to manipulate calendar information

GregorianCalendar today, independenceDay;

today = new GregorianCalendar();

independenceDay = new GregorianCalendar(1776, 6, 4);

//month 6 means July; 0 means January

Chapter 1 - 60

Retrieving Calendar Information

• This table shows the class constants for retrieving different pieces of calendar information from Date.

Chapter 1 - 61

Sample Calendar Retrieval

GregorianCalendar cal = new GregorianCalendar();//Assume today is Nov 9, 2003

System.out.print(“Today is ” +(cal.get(Calendar.MONTH)+1) + “/” +cal.get(Calendar.DATE) + “/” +cal.get(Calendar.YEAR));

Today is 11/9/2003Output

Chapter 1 - 62

Problem Statement

• Problem statement:

Write a loan calculator program that computes both monthly and total payments for a given loan amount, annual interest rate, and loan period.

Chapter 1 - 63

Overall Plan

• Tasks:– Get three input values: loanAmount,

interestRate, and loanPeriod.– Compute the monthly and total payments.– Output the results.

Chapter 1 - 64

Find the monthly payment• L: loan amount; R: monthly rate; • N :number of payments. • Suppose we must pay X per month. • Let yn be the amount of debt at month n. • Then

– y0 = L ; y1 = y0(1+R) – X = L(1+R) - X– y2 = y1(1+R) – X = [L(1+R) – X] (1+R) – X– = L(1+R)2 –X( 1 + (1+R) )– … – yN = yN-1 (1+R) – X = L(1+R)N – X[ 1 + (1+R) + … + (1+R)N-1 ]= 0

• Hence :– L(1+R)N = X [(1+R) N – 1 ] / [ (1+R) - 1 ] – X = LR / ( 1 – [1/(1+R)]N ).

Chapter 1 - 65

Required Classes

Chapter 1 - 66

Development Steps

We will develop this program in four steps:

1. Start with code to accept three input values.

2. Add code to output the results.

3. Add code to compute the monthly and total payments.

4. Update or modify code and tie up any loose ends.

Chapter 1 - 67

Step 1 Design

• Call the showInputDialog method to accept three input values: – loan amount, – annual interest rate, – loan period.

• Data types are

Input Format Data Typeloan amount dollars and cents double

annual interest rate in percent (e.g.,12.5)

double

loan period in years int

Chapter 1 - 68

Step 1 Code

Directory: Chapter3/Step1

Source File: Ch3LoanCalculator.java

Directory: Chapter3/Step1

Source File: Ch3LoanCalculator.java

Program source file is too big to list here. From now on, we askyou to view the source files using your Java IDE.

Chapter 1 - 69

Step 1 Test

• In the testing phase, we run the program multiple times and verify that– we can enter three input values– we see the entered values echo-printed correctly

on the standard output window

Chapter 1 - 70

Step 2 Design

• We will consider the display format for out.• Two possibilities are (among many others)

Chapter 1 - 71

Step 2 Code

Directory: Chapter3/Step2

Source File: Ch3LoanCalculator.java

Directory: Chapter3/Step2

Source File: Ch3LoanCalculator.java

Chapter 1 - 72

Step 2 Test

• We run the program numerous times with different types of input values and check the output display format.

• Adjust the formatting as appropriate

Chapter 1 - 73

Step 3 Design• The formula to compute the geometric

progression is the one we can use to compute the monthly payment.

• The formula requires the loan period in months and interest rate as monthly interest rate.

• So we must convert the annual interest rate (input value) to a monthly interest rate (per the formula), and the loan period to the number of monthly payments.– (1 + month_rate )12 = 1+ year_rate

-> month_rate = log(1+year_rate) /log 12 -1.

instead of year_rate /12.

Chapter 1 - 74

Step 3 Code

Directory: Chapter3/Step3

Source File: Ch3LoanCalculator.java

Directory: Chapter3/Step3

Source File: Ch3LoanCalculator.java

Chapter 1 - 75

Step 3 Test

• We run the program numerous times with different types of input values and check the results.

Chapter 1 - 76

Step 4: Finalize

• We will add a program description• We will format the monthly and total payments to

two decimal places using DecimalFormat.– DecimalFormat df = new DecimalFormat( “0.00” );

Directory: Chapter3/Step4

Source File: Ch3LoanCalculator.java

Chapter 1 - 77

Programming Assignment 1

• Chapter 3, Exercise 24 (p147)• Develop an application that reads a purchase

price and an amount tendered and then displays the change in dollars, quarteres, dimes, nickles, and pennies.– Two input values areentered in cents, for example, 3480

for $34.80 and 70 for $0.70.– Use any appropriate techniques for input and output.

• Name your class : HW1• Remember to give your name & register number in

the program.• due : 4/13.

Chapter 1 - 78

The format of the output

Purchase Price: $ 34.80

Amount Tendered: $ 40.00

Your change is : $ 5.20

5 one-dollar bill(s)

0 quarter(s)

2 dime(s)

0 nuckel(s)

0 penn(y/ies)

Thank you for your business. Com back soon.