Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 Numerical Data Animated Version."— Presentation transcript:

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 Arithmetic Expression a * (b + - (c / d ) / e ) * ( f – g % h ) 1 2 3 4 5 6 7 8

18 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.

19 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

20 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

21 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

22 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.

23 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)

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 Sample Code Fragment

30 Console Window

31 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

32 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

33 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

34 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

35 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

36

37 Console Window

38 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.

39 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 exp ( double a ); returns the natural number e ( 2.7718 …) raised to the power of a –double random(); 0.0 – 1.0

40 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) See in Table 3.7 in the book (109 p)

41 Quick Check What’s wrong with the following ? y = ( 1 / 2) * Math.sqrt ( X) ; y = sqrt ( 38.0 ); y = Math.exp (2, 3 ); y = math.sqrt ( b*b – 4 * a * c ) / ( 2 * a );

42 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

43 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)

44 © 2004 Pearson Addison-Wesley. All rights reserved 3-44 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); }

45 Console Window

46


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

Similar presentations


Ads by Google