Upcoming SlideShare
×

MELJUN CORTES -Java Numerical Data

301 views
232 views

Published on

MELJUN CORTES -Java Numerical Data

0 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
Your message goes here
• Be the first to comment

• Be the first to like this

Views
Total views
301
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
3
0
Likes
0
Embeds 0
No embeds

No notes for slide

MELJUN CORTES -Java Numerical Data

1. 1. Chapter 3- JAVA NumericalExpression Numerical Data MELJUN CORTES,MBA,MPA,BSCS,ACS
2. 2. Chapter 3 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. MELJUN CORTES,MBA,MPA,BSCS,ACS
3. 3. Chapter 3 Objectives, cont. After you have read and studied this chapter, you should be able to • Write mathematical expressions, using methods in the Math class. • Use the GregorianCalendar class in manipulating date information such as year, month, and day. • Use the DecimalFormat class to format numerical data. MELJUN CORTES,MBA,MPA,BSCS,ACS
4. 4. Chapter 3 Objectives, cont. After you have read and studied this chapter, you should be able to • Convert input string values to numerical data. • Apply the incremental development technique in writing programs. • (Optional) Describe how integers and real numbers are represented in memory. • Input data by using System.in and output data using System.out. MELJUN CORTES,MBA,MPA,BSCS,ACS
5. 5. 3.1 Variables To compute the sum and the difference of x and y in a program, we must first declare what kind of data will be assigned to them. After we assign values to them, we can compute their sum and difference. MELJUN CORTES,MBA,MPA,BSCS,ACS
6. 6. 3.1 Variables When a declaration, such as int x, y; is made, memory locations to store data values for x and y are allocated. These memory locations are called variables, and x and y are the names we associate with the memory locations. MELJUN CORTES,MBA,MPA,BSCS,ACS
7. 7. 3.1 Variables A variable has three properties: • A memory location to store the value. • The type of data stored in the memory location. • The name used to refer to the memory location. MELJUN CORTES,MBA,MPA,BSCS,ACS
8. 8. 3.1 Variables The syntax for declaring variables is <data type> <variables>; where <variables> is a sequence of identifiers separated by commas. Every variable we use in a program must be declared. MELJUN CORTES,MBA,MPA,BSCS,ACS
9. 9. 3.1 Variables There are six numerical data types in Java: • byte • short • int • long • float • double Data types byte, short, int, and long are for integers. Float and double are for real numbers. MELJUN CORTES,MBA,MPA,BSCS,ACS
10. 10. 3.1 Variables At the time a variable is declared, it can also be initialized. int count = 10, height = 34; We assign a value to a variable by using an assignment statement. Do not confuse mathematical equality and assignment. The following is not valid Java code: 4 + 5 = x; MELJUN CORTES,MBA,MPA,BSCS,ACS
11. 11. 3.1 Variables The only difference between a variable for numbers and a variable for objects is the contents in the memory locations. • For numbers, a variable contains the numerical value itself. • For objects, a variable contains an address where the object is stored. MELJUN CORTES,MBA,MPA,BSCS,ACS
12. 12. Fig. 3.1 A diagram showing how two memory locations (variables) are declared, and values are assigned to them. MELJUN CORTES,MBA,MPA,BSCS,ACS
13. 13. Fig. 3.2 A difference between object declaration and numerical data declaration. MELJUN CORTES,MBA,MPA,BSCS,ACS
14. 14. 3.1 Variables We use the new command to create an object. Objects are called reference data types, because the contents are addresses that refer to memory locations where the objects are actually stored. Numerical data are called primitive data types. MELJUN CORTES,MBA,MPA,BSCS,ACS
15. 15. Fig. 3.3 An effect of assigning the content of one variable to another. MELJUN CORTES,MBA,MPA,BSCS,ACS
16. 16. 3.2 Arithmetic Expressions Arithmetic operators in Java MELJUN CORTES,MBA,MPA,BSCS,ACS
17. 17. 3.2 Arithmetic Expressions An illustration of a subexpression in the expression x + 3 * y MELJUN CORTES,MBA,MPA,BSCS,ACS
18. 18. 3.2 Arithmetic Expressions Precedence rules for arithmetic operators and parentheses MELJUN CORTES,MBA,MPA,BSCS,ACS
19. 19. 3.2 Arithmetic Expressions Rules for arithmetic promotion MELJUN CORTES,MBA,MPA,BSCS,ACS
20. 20. 3.3 Constants If we want a variable to remain fixed, we use a constant. A constant is declared in a manner similar to a variable, but with the additional reserved word final. final double PI = 3.14159; final int MONTHS_IN_YEAR = 12; MELJUN CORTES,MBA,MPA,BSCS,ACS
21. 21. 3.3 Constants If a literal constant contains a decimal point, it is of type double by default. To designate a literal constant of type float, append a letter f or F to the number: 2 * PI * 345.79F MELJUN CORTES,MBA,MPA,BSCS,ACS
22. 22. 3.3 Constants Numbers in scientific notation, such as Number x 10exponent are expressed in Java using the syntax <number> E <exponent> 12.40e+209 29.009E-102 MELJUN CORTES,MBA,MPA,BSCS,ACS
23. 23. 3.4 Getting Numerical Input Values Wrapper classes are used to perform necessary type conversions, such as converting a String object to a numerical value. MELJUN CORTES,MBA,MPA,BSCS,ACS
24. 24. 3.4 Getting Numerical Input Values /* Chapter 3 Sample Program: Compute Area and Circumference File: Ch3Circle.java */ import javax.swing.*; import java.text.*; class Ch3Circle { public static void main( String [] args ) { final double PI = 3.14159; String radiusStr; MELJUN CORTES,MBA,MPA,BSCS,ACS
25. 25. 3.4 Getting Numerical Input Values double radius, area, circumference; 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); } } MELJUN CORTES,MBA,MPA,BSCS,ACS
26. 26. 3.4 Getting Numerical Input Values An illustration of how the compiler interprets an overloaded operator. int x = 1; int y = 2; String output = “test” + x + y; String output = x + y + “test”; MELJUN CORTES,MBA,MPA,BSCS,ACS
27. 27. Fig. 3.4 The dialog that appears when the input value 2.35 was entered into the Ch3Circle program. MELJUN CORTES,MBA,MPA,BSCS,ACS
28. 28. Fig. 3.5 The result of formatting the output values by using a DecimalFormat object. MELJUN CORTES,MBA,MPA,BSCS,ACS
29. 29. 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. MELJUN CORTES,MBA,MPA,BSCS,ACS
30. 30. Fig. 3.6 The standard output window for displaying multiple lines of text. MELJUN CORTES,MBA,MPA,BSCS,ACS
31. 31. 3.5 Standard Output We use the print method to output a value. The print method will continue printing from the end of the currently displayed output. MELJUN CORTES,MBA,MPA,BSCS,ACS
32. 32. Fig. 3.7 Result of executing System.out.print(“Hello, Dr. Caffeine.”). MELJUN CORTES,MBA,MPA,BSCS,ACS
33. 33. Fig. 3.8 Result of sending five print messages to System.out of Figure 3.7. MELJUN CORTES,MBA,MPA,BSCS,ACS
34. 34. 3.5 Standard Output The print method will do the necessary type conversion if we pass numerical data. We can print an argument and skip to the next line so that subsequent output will start on the next line by using println instead of print. MELJUN CORTES,MBA,MPA,BSCS,ACS
35. 35. Fig. 3.9 The result of mixing print with four println messages to System.out. MELJUN CORTES,MBA,MPA,BSCS,ACS
36. 36. 3.6 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. To input primitive data values, we use the Scanner class (from Java 2 SDK 1.5). MELJUN CORTES,MBA,MPA,BSCS,ACS
37. 37. Heres a sample code to input one integer and one double:Scanner scanner;scanner = Scanner.create(System.in);int num = scanner.nextInt();double val = scanner.nextDouble(); MELJUN CORTES,MBA,MPA,BSCS,ACS
38. 38. Common Methods: 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(); MELJUN CORTES,MBA,MPA,BSCS,ACS
39. 39. 3.7 The Math Class The Math class in the java.lang package contains class methods for commonly used mathematical functions. Table 3.6 contains a partial list of class methods available in the Math class. MELJUN CORTES,MBA,MPA,BSCS,ACS
40. 40. 3.8 The GregorianCalendar Class The GregorianCalendar class is useful in manipulating calendar information such as year, month, and day. Note that the first month of the year, January, is represented by 0. MELJUN CORTES,MBA,MPA,BSCS,ACS
41. 41. Fig. 3.12 Result of running the Ch3TestCalendar program at November 11, 2002, 6:13 p.m. MELJUN CORTES,MBA,MPA,BSCS,ACS
42. 42. 3.9 Sample Development: Loan Calculator Program flow: • Get three input values: loanAmount, interestRate, and loanPeriod. • Compute the monthly and total payments. • Output the results. MELJUN CORTES,MBA,MPA,BSCS,ACS
43. 43. Fig. 3.13 The object diagram for the program LoanCalculator. MELJUN CORTES,MBA,MPA,BSCS,ACS
44. 44. 3.9 Sample Development: Loan Calculator Steps of implementation: 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. MELJUN CORTES,MBA,MPA,BSCS,ACS
45. 45. 3.9 Sample Development: Loan Calculator Step 1 Development: Input Three Data Values Call the showInputDialog method to accept three input values: • loan amount, • annual interest rate, • loan period. MELJUN CORTES,MBA,MPA,BSCS,ACS
46. 46. 3.9 Sample Development: Loan Calculator /* Chapter 3 Sample Development: Loan Calculator (Step 1) File: Step1/Ch3LoanCalculator.java Step 1: Input Data Values */ import javax.swing.*; class Ch3LoanCalculator { public static void main (String[] args) { double loanAmount, annualInterestRate; int loanPeriod; String inputStr; MELJUN CORTES,MBA,MPA,BSCS,ACS
47. 47. 3.9 Sample Development: Loan Calculator //get input values inputStr = JOptionPane.showInputDialog(null, "Loan Amount (Dollars+Cents):"); loanAmount = Double.parseDouble(inputStr); inputStr = JOptionPane.showInputDialog(null, "Annual Interest Rate (e.g., 9.5):"); annualInterestRate = Double.parseDouble(inputStr); inputStr = JOptionPane.showInputDialog(null, "Loan Period - # of years:"); loanPeriod = Integer.parseInt(inputStr); MELJUN CORTES,MBA,MPA,BSCS,ACS
48. 48. 3.9 Sample Development: Loan Calculator //echo print the input values System.out.println("Loan Amount: \$" + loanAmount); System.out.println("Annual Interest Rate: " + annualInterestRate + "%"); System.out.println("Loan Period (years): " + loanPeriod); } } MELJUN CORTES,MBA,MPA,BSCS,ACS
49. 49. 3.9 Sample Development: Loan Calculator Step 2 Development: Output Values We must determine an appropriate format to display the computed results, so that the results will be comprehensible to the user. MELJUN CORTES,MBA,MPA,BSCS,ACS
50. 50. Fig. 3.14 Two display formats: One with input values displayed, and the other with only the computed values displayed. MELJUN CORTES,MBA,MPA,BSCS,ACS
51. 51. 3.9 Sample Development: Loan Calculator /* Chapter 3 Sample Development: Loan Calculator (Step 2) File: Step2/Ch3LoanCalculator.java Step 2: Display the Result */ import javax.swing.*; class Ch3LoanCalculator { public static void main (String[] args) { double loanAmount, annualInterestRate; double monthlyPayment, totalPayment; int loanPeriod; String inputStr; MELJUN CORTES,MBA,MPA,BSCS,ACS
52. 52. 3.9 Sample Development: Loan Calculator //get input values inputStr = JOptionPane.showInputDialog(null, "Loan Amount (Dollars+Cents):"); loanAmount = Double.parseDouble(inputStr); inputStr = JOptionPane.showInputDialog(null, "Annual Interest Rate (e.g., 9.5):"); annualInterestRate = Double.parseDouble(inputStr); inputStr = JOptionPane.showInputDialog(null, "Loan Period - # of years:"); loanPeriod = Integer.parseInt(inputStr); MELJUN CORTES,MBA,MPA,BSCS,ACS
53. 53. 3.9 Sample Development: Loan Calculator //compute the monthly and total payments monthlyPayment = 132.15; totalPayment = 15858.10; //display the result System.out.println("Loan Amount: \$" + loanAmount); System.out.println("Annual Interest Rate: " + annualInterestRate + "%"); System.out.println("Loan Period (years): " + loanPeriod); System.out.println("n"); //skip two lines System.out.println("Monthly payment is \$ " + monthlyPayment); System.out.println(" TOTAL payment is \$ " + totalPayment); } } MELJUN CORTES,MBA,MPA,BSCS,ACS
54. 54. 3.9 Sample Development: Loan Calculator Step 3 Development: Compute Loan Amount Complete the program by implementing the formula derived in the design phase. 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. MELJUN CORTES,MBA,MPA,BSCS,ACS
55. 55. 3.9 Sample Development: Loan Calculator /* Chapter 3 Sample Development: Loan Calculator (Step 3) File: Step3/Ch3LoanCalculator.java Step 3: Compute the monthly and total payments */ import javax.swing.*; class Ch3LoanCalculator { public static void main (String[] args) { final int MONTHS_IN_YEAR = 12; double loanAmount, annualInterestRate, monthlyPayment, totalPayment; double monthlyInterestRate; int loanPeriod, numberOfPayments; MELJUN inputStr; String CORTES,MBA,MPA,BSCS,ACS
56. 56. 3.9 Sample Development: Loan Calculator //get input values inputStr = JOptionPane.showInputDialog(null, "Loan Amount(Dollars+Cents):"); loanAmount = Double.parseDouble(inputStr); inputStr = JOptionPane.showInputDialog(null, "Annual Interest Rate (e.g., 9.5):"); annualInterestRate=Double.parseDouble(inputStr); inputStr = JOptionPane.showInputDialog(null, "Loan Period - # of years:"); loanPeriod = Integer.parseInt(inputStr); MELJUN CORTES,MBA,MPA,BSCS,ACS
57. 57. 3.9 Sample Development: Loan Calculator //compute the monthly and total payments monthlyInterestRate = annualInterestRate / MONTHS_IN_YEAR / 100; numberOfPayments = loanPeriod * MONTHS_IN_YEAR; monthlyPayment = (loanAmount * monthlyInterestRate) / (1 - Math.pow(1/(1 + monthlyInterestRate), numberOfPayments ) ); totalPayment = monthlyPayment * numberOfPayments; MELJUN CORTES,MBA,MPA,BSCS,ACS
58. 58. 3.9 Sample Development: Loan Calculator //display the result System.out.println("Loan Amount: \$" + loanAmount); System.out.println("Annual Interest Rate: " + annualInterestRate + "%"); System.out.println("Loan Period (years): " + loanPeriod); System.out.println("n"); //skip two lines System.out.println("Monthly payment is \$ " + monthlyPayment); System.out.println(" TOTAL payment is \$ " + totalPayment); } } MELJUN CORTES,MBA,MPA,BSCS,ACS
59. 59. 3.9 Sample Development: Loan Calculator Step 4 Development: Finishing Up Finalize the program by making necessary modifications or additions. We will add a program description and format the monthly and total payments to two decimal places. MELJUN CORTES,MBA,MPA,BSCS,ACS
60. 60. 3.9 Sample Development: Loan Calculator /* Chapter 3 Sample Development: Loan Calculator (Step 4) File: Step4/Ch3LoanCalculator.java Step 4: Finalize the program */ import javax.swing.*; import java.text.*; class Ch3LoanCalculator { public static void main (String[] args) { final int MONTHS_IN_YEAR = 12; double loanAmount, annualInterestRate; double monthlyPayment, totalPayment; double monthlyInterestRate; int loanPeriod, numberOfPayments; String inputStr; DecimalFormat df = new DecimalFormat("0.00"); MELJUN CORTES,MBA,MPA,BSCS,ACS
61. 61. 3.9 Sample Development: Loan Calculator //describe the program System.out.println("This program computes the monthly and total"); System.out.println("payments for a given loan amount, annual "); System.out.println("interest rate, and loan period."); System.out.println("Loan amount in dollars and cents, e.g., 12345.50"); System.out.println("Annual interest rate in percentage, e.g., 12.75"); System.out.println("Loan period in number of years, e.g., 15"); System.out.println("n"); //skip two lines MELJUN CORTES,MBA,MPA,BSCS,ACS
62. 62. 3.9 Sample Development: Loan Calculator //get input values inputStr = JOptionPane.showInputDialog(null, "Loan Amount(Dollars+Cents):"); loanAmount = Double.parseDouble(inputStr); inputStr = JOptionPane.showInputDialog(null, "Annual Interest Rate (e.g., 9.5):"); annualInterestRate = Double.parseDouble(inputStr); inputStr = JOptionPane.showInputDialog(null, "Loan Period - # of years:"); loanPeriod = Integer.parseInt(inputStr); MELJUN CORTES,MBA,MPA,BSCS,ACS
63. 63. 3.9 Sample Development: Loan Calculator //compute the monthly and total payments monthlyInterestRate = annualInterestRate / MONTHS_IN_YEAR / 100; numberOfPayments = loanPeriod * MONTHS_IN_YEAR; monthlyPayment = (loanAmount * monthlyInterestRate) / (1 - Math.pow(1/(1 + monthlyInterestRate), numberOfPayments ) ); totalPayment = monthlyPayment * numberOfPayments; MELJUN CORTES,MBA,MPA,BSCS,ACS
64. 64. 3.9 Sample Development: Loan Calculator //display the result System.out.println("Loan Amount: \$" + loanAmount); System.out.println("Annual Interest Rate: " + annualInterestRate + "%"); System.out.println("Loan Period (years): " + loanPeriod); System.out.println("n"); //skip two lines System.out.println("Monthly payment is \$ " + df.format(monthlyPayment)); System.out.println(" TOTAL payment is \$ " + df.format(totalPayment)); } } MELJUN CORTES,MBA,MPA,BSCS,ACS