Bài giảng Chapter 3: Bài giảng Chapter

Tài liệu Bài giảng Chapter 3: Bài giảng Chapter: Chapter 3Numerical Data©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 3 ObjectivesAfter 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 3 Objectives, cont.After you have read and studied this chapter, you should be able toWrite 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 3 Objectives, cont.After you have read and studied this chapter, you should be able toConvert input string values to num...

ppt65 trang | Chia sẻ: honghanh66 | Lượt xem: 904 | Lượt tải: 0download
Bạn đang xem trước 20 trang mẫu tài liệu Bài giảng Chapter 3: Bài giảng Chapter, để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên
Chapter 3Numerical Data©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 3 ObjectivesAfter 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 3 Objectives, cont.After you have read and studied this chapter, you should be able toWrite 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 3 Objectives, cont.After you have read and studied this chapter, you should be able toConvert 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.1 VariablesTo 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.1 VariablesWhen a declaration, such asint 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.1 VariablesA 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.1 VariablesThe syntax for declaring variables is ;where is a sequence of identifiers separated by commas. Every variable we use in a program must be declared.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.1 VariablesThere are six numerical data types in Java:byteshortintlong floatdoubleData types byte, short, int, and long are for integers.Float and double are for real numbers.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.1 VariablesAt 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; ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.1 VariablesThe 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 3.1A diagram showing how two memory locations (variables) are declared, and values are assigned to them.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 3.2A difference between object declaration and numerical data declaration.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.1 VariablesWe 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 3.3An effect of assigning the content of one variable to another.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.2 Arithmetic ExpressionsArithmetic operators in Java©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.2 Arithmetic ExpressionsAn illustration of a subexpression in the expression x + 3 * y©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.2 Arithmetic ExpressionsPrecedence rules for arithmetic operators and parentheses©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.2 Arithmetic ExpressionsRules for arithmetic promotion©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.3 ConstantsIf 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;©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.3 ConstantsIf 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©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.3 ConstantsNumbers in scientific notation, such as Number x 10exponentare expressed in Java using the syntax E 12.40e+20929.009E-102©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.4 Getting Numerical Input ValuesWrapper classes are used to perform necessary type conversions, such as converting a String object to a numerical value.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.4 Getting Numerical Input Values/*Chapter 3 Sample Program: Compute Area and CircumferenceFile: Ch3Circle.java*/import javax.swing.*;import java.text.*;class Ch3Circle { public static void main( String [] args ) { final double PI = 3.14159; String radiusStr; ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.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); }}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.4 Getting Numerical Input ValuesAn 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”;©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 3.4The dialog that appears when the input value 2.35 was entered into the Ch3Circle program.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 3.5The result of formatting the output values by using a DecimalFormat object.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.5 Standard OutputThe 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. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 3.6The standard output window for displaying multiple lines of text. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.5 Standard OutputWe use the print method to output a value.The print method will continue printing from the end of the currently displayed output.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 3.7Result of executing System.out.print(“Hello, Dr. Caffeine.”).©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 3.8Result of sending five print messages to System.out of Figure 3.7.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.5 Standard OutputThe 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 3.9The result of mixing print with four println messages to System.out.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.6 Standard InputThe technique of using System.in to input data is called standard input.Associating a BufferedReader object to the System.in object allows us to read a single line of text, then convert it to a value of a primitive data type. Using the intermediate InputStreamReader object allows us to read a single character at a time. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 3.10How the sequence of I/O objects adds greater capabilities.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 3.11Sample interaction using System.in and System.out.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.6 Standard InputCalling the readLine method can result in an error condition called an exception.To avoid this problem, add the clause throws IOException to the method declaration whenever a method includes a call to the readLine method. public static void main(String [] args) throws IOException {... String input = bufReader.readLine();...}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.7 The Math ClassThe 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. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.8 The GregorianCalendar ClassThe 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 3.12Result of running the Ch3TestCalendar program at November 11, 2002, 6:13 p.m.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.9 Sample Development: Loan CalculatorProgram flow:Get three input values: loanAmount, interestRate, and loanPeriod.Compute the monthly and total payments.Output the results. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 3.13The object diagram for the program LoanCalculator.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.9 Sample Development: Loan CalculatorSteps of implementation:Start with code to accept three input values.Add code to output the results.Add code to compute the monthly and total payments.Update or modify code and tie up any loose ends.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.9 Sample Development: Loan CalculatorStep 1 Development: Input Three Data ValuesCall the showInputDialog method to accept three input values: loan amount, annual interest rate, loan period.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.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; ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.9 Sample Development: Loan Calculator//get input valuesinputStr = 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); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.9 Sample Development: Loan Calculator//echo print the input valuesSystem.out.println("Loan Amount: $" + loanAmount);System.out.println("Annual Interest Rate: " + annualInterestRate + "%");System.out.println("Loan Period (years): " + loanPeriod); }}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.9 Sample Development: Loan CalculatorStep 2 Development: Output ValuesWe must determine an appropriate format to display the computed results, so that the results will be comprehensible to the user.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 3.14Two display formats: One with input values displayed, and the other with only the computed values displayed. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.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; ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.9 Sample Development: Loan Calculator//get input valuesinputStr = 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); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.9 Sample Development: Loan Calculator//compute the monthly and total paymentsmonthlyPayment = 132.15;totalPayment = 15858.10;//display the resultSystem.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 linesSystem.out.println("Monthly payment is $ " + monthlyPayment);System.out.println(" TOTAL payment is $ " + totalPayment); }}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.9 Sample Development: Loan CalculatorStep 3 Development: Compute Loan AmountComplete 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.9 Sample Development: Loan Calculator/*Chapter 3 Sample Development: Loan Calculator (Step 3)File: Step3/Ch3LoanCalculator.javaStep 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; String inputStr; ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.9 Sample Development: Loan Calculator//get input valuesinputStr = 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);©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.9 Sample Development: Loan Calculator//compute the monthly and total paymentsmonthlyInterestRate = annualInterestRate / MONTHS_IN_YEAR / 100;numberOfPayments = loanPeriod * MONTHS_IN_YEAR;monthlyPayment = (loanAmount * monthlyInterestRate) / (1 - Math.pow(1/(1 + monthlyInterestRate), numberOfPayments ) );totalPayment = monthlyPayment * numberOfPayments;©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.9 Sample Development: Loan Calculator//display the resultSystem.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 linesSystem.out.println("Monthly payment is $ " + monthlyPayment);System.out.println(" TOTAL payment is $ " + totalPayment); }}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.9 Sample Development: Loan CalculatorStep 4 Development: Finishing UpFinalize 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.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"); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.9 Sample Development: Loan Calculator//describe the programSystem.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©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.9 Sample Development: Loan Calculator//get input valuesinputStr = 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);©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.9 Sample Development: Loan Calculator//compute the monthly and total paymentsmonthlyInterestRate = annualInterestRate / MONTHS_IN_YEAR / 100;numberOfPayments = loanPeriod * MONTHS_IN_YEAR;monthlyPayment = (loanAmount * monthlyInterestRate) / (1 - Math.pow(1/(1 + monthlyInterestRate), numberOfPayments ) );totalPayment = monthlyPayment * numberOfPayments; ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.3.9 Sample Development: Loan Calculator//display the resultSystem.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 linesSystem.out.println("Monthly payment is $ " + df.format(monthlyPayment));System.out.println(" TOTAL payment is $ " + df.format(totalPayment)); }}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Các file đính kèm theo tài liệu này:

  • pptchap_3_5882.ppt