©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 Numerical Data Animated Version.

Slides:



Advertisements
Similar presentations
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 3 Numerical Data.
Advertisements

Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
CS 180 Recitation 9 / {06, 07} / Reminders Assignment 1 was due last night. Assignment 2 is available & due in 1 week. 10:00pm, Wednesday, September.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 3 Console Output Keyboard Input Numerical.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 3 Sample Development Loan Calculator.
Chapter 3 Using Classes and Objects. Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 Numerical Data.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 3 Console Output Keyboard Input Numerical.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
INF 523Q Chapter 2: Objects and Primitive Data (Examples)
Copyright © 2012 Pearson Education, Inc. Chapter 3 Using Classes and Objects Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
Static Class Members Wrapper Classes Autoboxing Unboxing.
بسم الله الرحمن الرحيم CPCS203: Programming II. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display., Modifications by Dr.
Chapter 3b Standard Input and Output Sample Development.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Chapter 3 Using Classes and Objects. © 2004 Pearson Addison-Wesley. All rights reserved3-2 Outline Last Time: Creating Objects The GregorianCalendar Class.
Using Classes and Objects Chapters 3 Section 3.3 Packages Section 3.4 Random Class Section 3.5 Math Class Section 3.7 Enumerated Types Instructor: Scott.
Expressions, Data Conversion, and Input
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
COS 312 DAY 3 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 1 DUE right now Assignment 2 Posted – Due Feb 5 prior to class Using Classes and Objects.
Chapter 3 Using Classes and Objects. Chapter Scope Creating objects Services of the String class The Java API class library The Random and Math classes.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 3 Numerical Data.
CS1101X: Programming Methodology Recitation 1 Java Basics Numerical Data.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 Numerical Data Animated Version.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 3: Numerical Data Manipulating Numbers Variables.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Copyright © 2012 Pearson Education, Inc. Chapter 3 Using Classes and Objects Java Software Solutions Foundations of Program Design Seventh Edition John.
Outline Creating Objects The String Class The Random and Math Classes Formatting Output Enumerated Types Wrapper Classes Components and Containers Images.
***** SWTJC STEM ***** Chapter 3-1 cg 39 Math Class The Math class provides a convenient way to access higher math functions. The Math class is automatically.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 3 Console Output Keyboard Input Numerical.
Using Classes and Objects. We can create more interesting programs using predefined classes and related objects Chapter 3 focuses on: Object creation.
© 2004 Pearson Addison-Wesley. All rights reserved September 7, 2007 Formatting Output & Enumerated Types & Wrapper Classes ComS 207: Programming I (in.
CSE 1201 Object Oriented Programming Using Classes and Objects.
Using Classes and Objects (Chapter 3) Copyright © 2012 Pearson Education, Inc.
1 Lecture 5 More Programming Constructs Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
Numeric Data Types There are six numeric data types: byte, short, int, long, float, and double. Sample variable declarations: int i, j, k; float numberOne,
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Chapter 3 Numerical Data. Objectives After you have read and studied this chapter, you should be able to Select proper types for numerical data. Write.
Outline Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 3: Using Classes and Objects Coming up: Creating Objects.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
1 CMPT 126 Java Basics Using Classes and Objects.
CSCI 1100/1202 January 18, Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric.
Outline Creating Objects The String Class The Random and Math Classes Formatting Output Enumerated Types Wrapper Classes Components and Containers Images.
Using Classes and Objects We can create more interesting programs using predefined classes and related objects Chapter 3 focuses on: object creation and.
Data and Expressions. Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration.
M105 - Week 2 Chapter 3 Numerical Data 1 Prepared by: M105 Team - AOU - SAB.
© 2004 Pearson Addison-Wesley. All rights reserved January 27, 2006 Formatting Output & Enumerated Types & Wrapper Classes ComS 207: Programming I (in.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Formatting Output & Enumerated Types & Wrapper Classes
Intro to OOP with Java, C. Thomas Wu Numerical Data
CSC 1051 – Data Structures and Algorithms I
Multiple variables can be created in one declaration
Primitive and Reference Data Values
Chapter 3: Using Classes and Objects
Java Programming: From Problem Analysis to Program Design, 4e
Primitive and Reference Data Values
Pseudocode and Flowcharts
Increment and Decrement
Wrapper Classes The java.lang package contains wrapper classes that correspond to each primitive type: Primitive Type Wrapper Class byte Byte short Short.
Chapter 3 Numerical Data
Outline Creating Objects The String Class The Random and Math Classes
Presentation transcript:

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 Numerical Data Animated Version

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Objectives After you have read and studied this chapter, you should be able to Select proper types for numerical data. Write arithmetic expressions in Java. Evaluate arithmetic expressions using the precedence rules. Describe how the memory allocation works for objects and primitive data values. Write mathematical expressions, using methods in the Math class, Random. Use the GregorianCalendar class in manipulating date information such as year, month, and day. Use the DecimalFormat class to format numerical data Convert input string values to numerical data (Wrapper class)

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Variables and Numerical Data Types 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. There are six numerical data types: byte, short, int, long, float, and double. int x; int v, w, y; int count = 10, height = 34; Float numberOne, numberTwo

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Data Type Precisions The six data types differ in the precision of values they can store in memory.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Characters In Java, single characters are represented using the data type char. Character constants are written as symbols enclosed in single quotes. 'a' 'X' '7' '$' ',' '\n' Characters are stored in a computer memory using some form of encoding. each character corresponding to a unique number. ASCII, which stands for American Standard Code for Information Interchange, is one of the document coding schemes widely used today.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Character Sets Java uses Unicode, which includes ASCII, for representing char constants. The Unicode character set uses sixteen bits per character, allowing for 65,536 unique characters. Note the distinction between a primitive character variable, which holds only one character, and a String object, which can hold multiple characters

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ASCII Encoding For example, character 'O' is 79 (row value 70 + col value 9 = 79). O 9 70

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Character Processing Declaration and initialization char ch1, ch2 = ‘X’; Type conversion between int and char. System.out.print("ASCII code of character X is " + (int) ' X ' ); System.out.print("Character with ASCII code 88 is " + (char)88 ); This comparison returns true because ASCII value of 'A' is 65 while that of 'c' is 99. ‘A’ < ‘c’ char ch1 = 'X'; System.out.println(ch1); System.out.println( (int) ch1);

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Boolean A boolean value represents a true or false condition The reserved words true and false are the only valid values for a boolean type boolean done = false; A boolean variable can also be used to represent any two states, such as a light bulb being on or off Boolean variable in JAVA do not accept 0 as false and 1 as true

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 = ; 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.

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;

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Arithmetic Operators The following table summarizes the arithmetic operators available in Java. This is an integer division where the fractional part is truncated.

Increment and Decrement The increment and decrement operators use only one operand The increment operator ( ++ ),The decrement operator ( -- ) The increment and decrement operators can be applied in postfix form: count++, or prefix form: ++count When used as part of a larger expression, the two forms can have different effects

Assignment Operators There are many assignment operators in Java, including the following: Operator += -= *= /= %= Example x += y x -= y x *= y x /= y x %= y Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y

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. If two operators are the same precedence, then they are evaluated left to right for most operators.

Precedence Rules

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.

Primitive Data Declaration and Assignments Code State of Memory int firstNumber, secondNumber; firstNumber = 234; secondNumber = 87; A A int firstNumber, secondNumber; B B firstNumber = 234; secondNumber = 87; int firstNumber, secondNumber; firstNumber = 234; secondNumber = 87; firstNumber secondNumber A. A. Variables are allocated in memory. B. B. Values are assigned to variables

Assigning Numerical Data Code State of Memory int number; number = 237; number = 35; 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; number = 35; A A int number; B B number = 237; C C number = 35; C C. The value 35 overwrites the previous value

Assigning Objects Code State of Memory Customer customer; customer = new Customer( ); customer A. A. The variable is allocated in memory. Customer customer; customer = new Customer( ); A A Customer customer; B B customer = new Customer( ); 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

Having Two References to a Single Object Code State of Memory Customer clemens, twain; clemens = new Customer( ); twain = clemens; Customer clemens, twain, clemens = new Customer( ); twain = clemens; A A Customer clemens, twain; B B clemens = new Customer( ); C C twain = clemens; 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.

Aliases Two or more references that refer to the same object are called aliases of each other That creates an interesting situation: one object can be accessed using multiple reference variables Aliases can be useful, but should be managed carefully Changing an object through one reference changes it for all of its aliases, because there is really only one object. (this doesn’t work with Strings)

Garbage Collection When an object no longer has any valid references to it, it can no longer be accessed by the program The object is useless, and therefore is called garbage Java performs automatic garbage collection periodically, returning an object's memory to the system for future use In other languages, the programmer is responsible for performing garbage collection

Data Conversion Sometimes it is convenient to convert data from one type to another For example, in a particular situation we may want to treat an integer as a floating point value These conversions do not change the type of a variable or the value that's stored in it – they only convert a value as part of a computation

Data Conversion Conversions must be handled carefully to avoid losing information Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int ) Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short ) Boolean value cant be converted In Java, data conversions can occur in three ways: –assignment conversion –promotion –casting

Assignment Conversion Assignment conversion occurs when a value of one type is assigned to a variable of another If float money and int dollars the following converts the value in dollars to a float money = dollars Only widening conversions can happen via assignment, A higher precision value cannot be assigned to a lower precision variable. Note that the value or type of dollars did not change

Promotion Conversion Promotion happens automatically when operators in expressions convert their operands For example, if float sum and int count the value of count is converted to a floating point value to perform the following calculation: result = sum / count; The above expression is called a mixed expression. The promotion rules ensure that the data type of the expression will be the same as the data type of an operand whose type has the highest precision

Casting Casting is the most powerful, and dangerous, technique for conversion To cast, the type is put in parentheses in front of the value being converted ( ) (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.

Wrapper Classes The java.lang package contains wrapper classes that correspond to each primitive type: Primitive TypeWrapper Class byteByte shortShort intInteger longLong floatFloat doubleDouble charCharacter booleanBoolean voidVoid

Wrapper Classes The following declaration creates an Integer object which represents the integer 40 as an object Integer age = new Integer(40); An object of a wrapper class can be used in any situation where a primitive value will not suffice Wrapper classes are used to perform necessary type conversions, such as converting a String object to a numerical value 40 age

Wrapper Classes Wrapper classes also contain methods that help manage the associated type Integer ( int value) Constructor int intValue() double doubleValue () return the value of this integer as a corresponding primitive type static String toBinaryString ( int num); static String tohexString ( int num); Return a string representation static String toOctalString ( int num); EX : System.out.print (Integer.toBinaryString(6)); 110

Other Conversion Methods The Integer class contains a static method to convert an integer stored in a String to an int value: num = Integer.parseInt(str);

Wrapper Classes The wrapper classes often contain useful constants as well For example, the Integer class contains MIN_VALUE and MAX_VALUE which hold the smallest and largest int values Integer a = 5; System.out.print (a.MAX_VALUE); Because Some of the methods are static we can use the class name ( Integer.MAX_VALUE). We don’t need to use “new”.

Autoboxing Autoboxing is the automatic conversion of a primitive value to a corresponding wrapper object: Integer obj; int num = 42; obj = num; The reverse conversion (called unboxing) also occurs automatically as needed Integer obj=42; int num; num = obj;

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 = Math.PI * radius * radius; circumference = 2.0 * Math.PI * radius; JOptionPane.showMessageDialog(null, "Given Radius: " + radius + "\n" + "Area: " + area + "\n" + "Circumference: " + circumference);

Formatting Output It is often necessary to format values in certain ways so that they can be presented properly The Java standard class library contains classes that provide formatting capabilities The NumberFormat class allows you to format values as currency or percentages The DecimalFormat class allows you to format values based on a pattern Both are part of the java.text package

Formatting Output The NumberFormat class has static methods that return a formatter object ( no using new ) Static NumberFormat getCurrencyInstance() Static NumberFormat getPercentInstance() Each formatter object has a method called format that returns a string with the specified information in the appropriate format

Purchase.java import java.util.Scanner; import java.text.NumberFormat; public class Purchase { public static void main (String[] args) { final double TAX_RATE = 0.06; // 6% sales tax int quantity; double subtotal, tax, totalCost, unitPrice; Scanner scan = new Scanner (System.in); NumberFormat fmt1 = NumberFormat.getCurrencyInstance(); NumberFormat fmt2 = NumberFormat.getPercentInstance(); System.out.print ("Enter the quantity: "); quantity = scan.nextInt(); System.out.print ("Enter the unit price: "); unitPrice = scan.nextDouble(); subtotal = quantity * unitPrice; tax = subtotal * TAX_RATE; totalCost = subtotal + tax; // Print output with appropriate formatting System.out.println ("Subtotal: " + fmt1.format(subtotal)); System.out.println ("Tax: " + fmt1.format(tax) + " at " + fmt2.format(TAX_RATE)); System.out.println ("Total: " + fmt1.format(totalCost)); } Enter the quantity: 5 Enter the unit price: 3.87 Subtotal: $19.35 Tax: $1.16 at 6% Total: $20.51

Formatting Output The DecimalFormat class can be used to format a floating point value in various ways The DecimalFormat class unlike NumberFormat (must use New) For example, you can specify that the number should be truncated to three decimal places The constructor of the DecimalFormat class takes a string that represents a pattern for the formatted number import java.text.DecimalFormat; DecimalFormat fmt = new DecimalFormat ("0.###"); fmt.format(circumference); // circumference is double

The DecimalFormat Class Use a DecimalFormat object to format the numerical output. double num = ; DecimalFormat df = new DecimalFormat(“0.000”); //three decimal places System.out.print(num); System.out.print(df.format(num));

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) ); Table 3.7 in the textbook contains a list of class methods defined in the Math class.

The Math Class The Math class contains static constants: –PI, –The constant can be used through the class name Areaofcircle=radius*radius*Math.PI; These include: – int abs ( int num ); absolute value –double sqrt (double num ); square root –double sin (double angle); trigonometric functions –double ceil ( double num); the smallest number greater than num or equal. –double floor ( double num); the largest number less than num or equal. –double pow ( double num, double power); –double random(); 0.0 – 1.0

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)

Quadratic.java import java.util.Scanner; public class Quadratic { // Determines the roots of a quadratic equation. public static void main (String[] args) { int a, b, c; double discriminant, root1, root2; Scanner scan = new Scanner (System.in); System.out.print ("Enter the coefficient of x squared: "); a = scan.nextInt(); System.out.print ("Enter the coefficient of x: "); b = scan.nextInt(); System.out.print ("Enter the constant: "); c = scan.nextInt(); // Use the quadratic formula to compute the roots. discriminant = Math.pow(b, 2) - (4 * a * c); root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a); root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a); System.out.println ("Root #1: " + root1); System.out.println ("Root #2: " + root2); } -b ± b 2 -4ac 2a

The Random Class The Random class is part of the java.util package It provides methods that generate pseudorandom numbers A Random object performs complicated calculations based on a seed value to produce a stream of seemingly random values Random (); float nextFloat(); 0.0 ( inclusive) – 1.0 (exclusive) int nextInt(); int range ( +, -) int nextInt( int num); 0 – num-1

© 2004 Pearson Addison-Wesley. All rights reserved 3-46 RandomNumbers.java import java.util.Random; public class RandomNumbers { // Generates random numbers in various ranges. public static void main (String[] args) { Random generator = new Random(); int num1; float num2; num1 = generator.nextInt(); System.out.println ("A random integer: " + num1); num1 = generator.nextInt(10); System.out.println ("From 0 to 9: " + num1); num1 = generator.nextInt(10) + 1; System.out.println ("From 1 to 10: " + num1); num1 = generator.nextInt(15) + 20; System.out.println ("From 20 to 34: " + num1); num1 = generator.nextInt(20) - 10; System.out.println ("From -10 to 9: " + num1); num2 = generator.nextFloat(); System.out.println ("A random float (between 0-1): " + num2); num2 = generator.nextFloat() * 6; // 0.0 to num1 = (int)num2 + 1; System.out.println ("From 1 to 6: " + num1); }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Retrieving Calendar Information This table shows the class constants for retrieving different pieces of calendar information from Date.

Check Ch3TestCalender/ Ch3IndependenceDay/Ch3FindDayOfWeek 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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 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.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Overall Plan Tasks: –Get three input values: loanAmount, interestRate, and loanPeriod. –Compute the monthly and total payments. –Output the results.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Required Classes

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 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.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 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.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 2 Design We will consider the display format for out. Two possibilities are (among many others)

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 2 Code Directory: Chapter3/Step2 Source File: Ch3LoanCalculator.java Directory: Chapter3/Step2 Source File: Ch3LoanCalculator.java

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 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.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 3 Code Directory: Chapter3/Step3 Source File: Ch3LoanCalculator.java Directory: Chapter3/Step3 Source File: Ch3LoanCalculator.java

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 3 Test We run the program numerous times with different types of input values and check the results.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 4: Finalize We will add a program description We will format the monthly and total payments to two decimal places using DecimalFormat. Directory: Chapter3/Step4 Source File: Ch3LoanCalculator.java