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

Slides:



Advertisements
Similar presentations
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.
Advertisements

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 3 Console Output Keyboard Input Numerical.
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.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
Numerical Data Recitation – 01/30/2009
©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.
CS180 Recitation 3. Lecture: Overflow byte b; b = 127; b += 1; System.out.println("b is" + b); b is -128 byte b; b = 128; //will not compile! b went out.
INF 523Q Chapter 2: Objects and Primitive Data (Examples)
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
بسم الله الرحمن الرحيم CPCS203: Programming II. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display., Modifications by Dr.
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
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 Numerical Data Animated Version.
Chapter 2 Data and Expressions. © 2004 Pearson Addison-Wesley. All rights reserved2-2 Data and Expressions Let's explore some other fundamental programming.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 3: Numerical Data Manipulating Numbers Variables.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
CSE 1201 Object Oriented Programming Using Classes and Objects.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
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.
Programming in Java (COP 2250) Lecture 7 Chengyong Yang Fall, 2005.
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.
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.
Numeric Data Types There are six numeric data types: byte, short, int, long, float, and double.
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
CSC 1051 – Data Structures and Algorithms I
Data Conversion & Scanner Class
Multiple variables can be created in one declaration
Primitive and Reference Data Values
Type Conversion, Constants, and the String Object
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
Chapter 2: Basic Elements of Java
Objects and Primitive Data
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

Arithmetic Expression a * (b + - (c / d ) / e ) * ( f – g % h )

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)

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.

Sample Code Fragment

Console Window

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

Console Window

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 exp ( double a ); returns the natural number e ( …) raised to the power of a –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) See in Table 3.7 in the book (109 p)

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

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-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 num1 = (int)num2 + 1; System.out.println ("From 1 to 6: " + num1); }

Console Window