Download presentation
Presentation is loading. Please wait.
1
Chapter 1 - 1 Chapter 3 Numerical Data
2
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.
3
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.
4
Chapter 1 - 4 Integer types namerepresentation range byte 8-bit 2's complement -128~127 short 16-bit 2's complement -32768~32767 int 32-bit 2's complement -2147483648 to 2147483647 long 64-bit 2's complement -2 63 ~2 63 -1 (19 digits) char 16-bit Unicode '\u0000' to '\uffff‘ or 0 ~ 65535
5
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+308 Representation: 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.
6
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.
7
Chapter 1 - 7 b 31 b 30 b 29 b 26 b 28 b 27 b 25 b 16 b 17 b 18 b 19 b 21 b 20 b 22 b 23 b 24 es (exponent) b 15 b 14 b 13 b 10 b 12 b 11 b9b9 b0b0 b1b1 b2b2 b3b3 b5b5 b4b4 b6b6 b7b7 b8b8 m (man’tissa) value is determined as follows: 0. s = (b 31 == 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 (b 22.b 21 ---b 0 0) 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 = 01 8 10 22 IEEE 754 float-point single precision layout
8
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
9
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
10
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 literal not allowed
11
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
12
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 '.
13
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.
14
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: –" StringCharacters opt “ // empty string “” allowed StringCharacters: –StringCharacter –StringCharacters StringCharacter StringCharacter: –Any Character but not any of " \ CR LF –EscapeSequence
15
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’
16
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 */
17
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
18
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 ≠ 1 2.false ≠ 0 ≠ null
19
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.
20
Chapter 1 - 20 Manipulating Numbers In Java, to add two numbers x and y, we write x + y Before actual addition of the two numbers, we must declare their data type. If x and y are integer (variables), we write int x, y; or int x; int y;
21
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;
22
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;
23
Chapter 1 - 23 Data Type Precisions The six data types differ in the precision of values they can store in memory.
24
Chapter 1 - 24 Assignment Statements We assign a value to a variable using an assignment statements. The syntax is = ; Examples: sum = firstNumber + secondNumber; avg = (one + two + three) / 3.0;
25
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. division: 1.10 / 3 = 3; -10 / 3 = -3 2.10 / -3 = -3 ; -10 /-3 = 3. 3.10 / 0 Exception 10.0 /0 +Infinite
26
Chapter 1 - 26 Arithmetic Expression How does the expression x + 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)
27
Chapter 1 - 27 Precedence Rules
28
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;
29
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
30
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; long double. 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.
31
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
32
Chapter 1 - 32 Java Primitive Type Conversion rules LRLR boolea n byteshortcharintlongfloat doubl e boolean -NNNNNNN byteNot allowed -YCYesYYY shortNCast-CYYYY charNCC-YYYY intNCCC-YY* (loss) Y longNCCCC-Y* floatNCCCCC-Y double NCCCCCC-
33
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 ()
34
Chapter 1 - 34 Explicit Type Casting format: –( ) Example (float) x / 3 (int) (x / y * 3.0) Type case x to float and then divide it by 3. Type cast the result of the expression x / y * 3.0 to int.
35
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.
36
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. The reserved word final is used to declare constants. These are called literal constant.
37
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.
38
Chapter 1 - 38 Primitive Data Declaration and Assignments Code State of Memory int firstNumber, secondNumber; firstNumber = 234; secondNumber = 87; A A B B firstNumber secondNumber A. A. Variables are allocated in memory. B. B. Values are assigned to variables. 234 87
39
Chapter 1 - 39 Assigning Numerical Data Code State of Memory number A. A. The variable is allocated in memory. B. 237 number B. The value 237 is assigned to number. 237 int number; number = 237; A A B B C C number = 35; C. 35 237. C. The value 35 overwrites the previous value 237. 35
40
Chapter 1 - 40 Assigning Objects Code State of Memory customer A. A. The variable is allocated in memory. Customer customer; customer = new Customer( ); A A B B C C B. customer B. The reference to the new object is assigned to customer. Customer C. customer. C. The reference to another object overwrites the reference in customer. Customer
41
Chapter 1 - 41 Having Two References to a Single Object Code State of Memory Customer clemens, twain, clemens = new Customer( ); twain = clemens; A A B B C C A. A. Variables are allocated in memory. clemens twain B. clemens B. The reference to the new object is assigned to clemens. Customer C. clemens customer. C. The reference in clemens is assigned to customer.
42
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.
43
Chapter 1 - 43 Type Conversion Wrapper classes are used to perform necessary type conversions, such as converting a String object to a numerical value.Wrapper classes int age; String inputStr; inputStr = JOptionPane.showInputDialog( null, “Enter your age”); age = Integer.parseInt(inputStr);Integer
44
Chapter 1 - 44 Other Conversion Methods
45
Chapter 1 - 45 Sample Code Fragment //code fragment to input radius and output //area and circumference double radius, area, circumference; String radiusStr = JOptionPane.showInputDialog( null, "Enter radius: " ); radius = Double.parseDouble(radiusStr); //compute area and circumference area = PI * radius * radius; circumference = 2.0 * PI * radius; JOptionPane.showMessageDialog(null, "Given Radius: " + radius + "\n" + "Area: " + area + "\n" + "Circumference: " + circumference);
46
Chapter 1 - 46 Overloaded Operator + The plus operator + can mean two different operations, depending on the context. + 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”;
47
Chapter 1 - 47 The DecimalFormat Class Use a DecimalFormat object to format the numerical output.DecimalFormat 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
48
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. System.out
49
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.
50
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.” );
51
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“ );
52
Chapter 1 - 52 Static imports static import import 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“ );
53
Chapter 1 - 53 Standard Input The technique of using System.in to input data is called standard input.System –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; scanner = new Scanner(System.in); int num = scanner.nextInt();
54
Chapter 1 - 54 MethodExample 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:
55
Chapter 1 - 55 The Math class The Math class in the java.lang package contains class methods for commonly used mathematical functions.Math double num, x, y; x = …; y = …; num = Math.sqrt(Math.max(x,y)+12.4);
56
Chapter 1 - 56 Some Math Class Methods MethodDescription 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.
57
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) );
58
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));
59
Chapter 1 - 59 The GregorianCalendar Class Use a GregorianCalendar object to manipulate calendar informationGregorianCalendar GregorianCalendar today, independenceDay; today = new GregorianCalendar(); independenceDay = new GregorianCalendar(1776, 6, 4); //month 6 means July; 0 means January
60
Chapter 1 - 60 Retrieving Calendar Information This table shows the class constants for retrieving different pieces of calendar information from Date.
61
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/2003 Output
62
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.
63
Chapter 1 - 63 Overall Plan Tasks: –Get three input values: loanAmount, interestRate, and loanPeriod. –Compute the monthly and total payments. –Output the results.
64
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 y n be the amount of debt at month n. Then –y 0 = L ; y 1 = y 0 (1+R) – X = L(1+R) - X –y 2 = y 1 (1+R) – X = [L(1+R) – X] (1+R) – X – = L(1+R) 2 –X( 1 + (1+R) ) –… –y N = y N-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 ).
65
Chapter 1 - 65 Required Classes
66
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.
67
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 InputFormatData Type loan amountdollars and centsdouble annual interest ratein percent (e.g.,12.5) double loan periodin yearsint
68
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 ask you to view the source files using your Java IDE.
69
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
70
Chapter 1 - 70 Step 2 Design We will consider the display format for out. Two possibilities are (among many others)
71
Chapter 1 - 71 Step 2 Code Directory: Chapter3/Step2 Source File: Ch3LoanCalculator.java Directory: Chapter3/Step2 Source File: Ch3LoanCalculator.java
72
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
73
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.
74
Chapter 1 - 74 Step 3 Code Directory: Chapter3/Step3 Source File: Ch3LoanCalculator.java Directory: Chapter3/Step3 Source File: Ch3LoanCalculator.java
75
Chapter 1 - 75 Step 3 Test We run the program numerous times with different types of input values and check the results.
76
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
77
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.
78
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.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.