Download presentation
Presentation is loading. Please wait.
Published byVictoria Gibson Modified over 9 years ago
1
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 Numerical Data Animated Version
2
©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)
3
©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
4
©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.
5
©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.
6
©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
7
©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
8
©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);
9
©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
10
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.
11
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;
12
©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.
13
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
14
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
15
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.
16
Precedence Rules
17
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.
18
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. 234 87
19
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. 35 237. C. The value 35 overwrites the previous value 237. 35
20
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
21
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.
22
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)
23
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
24
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
25
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
26
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
27
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
28
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.
29
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
30
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
31
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
32
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);
33
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); 2147483647 Because Some of the methods are static we can use the class name ( Integer.MAX_VALUE). We don’t need to use “new”.
34
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;
35
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);
36
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
37
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
38
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
39
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
40
The DecimalFormat Class Use a DecimalFormat object to format the numerical output. double num = 123.45789345; DecimalFormat df = new DecimalFormat(“0.000”); //three decimal places System.out.print(num); System.out.print(df.format(num)); 123.45789345 123.458
41
The Math class The Math class in the java.lang package contains class methods for commonly used mathematical functions. double num, x, y; x = …; y = …; num = Math.sqrt(Math.max(x, y) + 12.4); Table 3.7 in the textbook contains a list of class methods defined in the Math class.
42
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
43
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)
44
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
45
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
46
© 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 5.999999 num1 = (int)num2 + 1; System.out.println ("From 1 to 6: " + num1); }
47
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 - 47 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
48
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 - 48 Retrieving Calendar Information This table shows the class constants for retrieving different pieces of calendar information from Date.
49
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
50
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 - 50 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.
51
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 - 51 Overall Plan Tasks: –Get three input values: loanAmount, interestRate, and loanPeriod. –Compute the monthly and total payments. –Output the results.
52
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 - 52 Required Classes
53
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 - 53 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.
54
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 - 54 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
55
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 - 55 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.
56
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 - 56 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
57
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 - 57 Step 2 Design We will consider the display format for out. Two possibilities are (among many others)
58
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 - 58 Step 2 Code Directory: Chapter3/Step2 Source File: Ch3LoanCalculator.java Directory: Chapter3/Step2 Source File: Ch3LoanCalculator.java
59
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 - 59 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
60
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 - 60 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.
61
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 - 61 Step 3 Code Directory: Chapter3/Step3 Source File: Ch3LoanCalculator.java Directory: Chapter3/Step3 Source File: Ch3LoanCalculator.java
62
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 - 62 Step 3 Test We run the program numerous times with different types of input values and check the results.
63
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 - 63 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
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.