©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 3 - 1 Chapter 3 Console Output Keyboard Input Numerical.

Slides:



Advertisements
Similar presentations
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 3 Numerical Data.
Advertisements

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.
Expressions ► An expression can be a single variable, or can include a series of variables. If an expression includes multiple variables they are combined.
©2004 Brooks/Cole Chapter 2 Variables, Values and Operations.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 3 Console Output Keyboard Input Numerical.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
CMT Programming Software Applications
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Odds and Ends  Formatted Output  Random numbers.
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Confirmation Dialog Formatting Output.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 Numerical Data.
Numerical Data Recitation – 01/30/2009
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.
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.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: IO *Standard Output *Formatting Decimal.
Expressions, Data Conversion, and Input
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 Numerical Data Animated Version.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Variable Declaration  It is possible to declare multiple variables of the same data type on the same line.  Ex. double hours, rate, total;  Variables.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chapter 2 part #4 Operator
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
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.
Chapter 2: Using Data.
©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. Chapter Chapter 3: Numerical Data Manipulating Numbers Variables.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 2 Basic Elements of Java.
Programming Process Programming in Java is an exercise in using pre-defined classes and writing new classes to fill in the gaps A procedure for determining.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 3 Console Output Keyboard Input Numerical.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 2A Reading, Processing and Displaying Data (Concepts)
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.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
CSCI 1100/1202 January 18, Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Fundamentals 2 1. Programs and Data Most programs require the temporary storage of data. The data to be processed is stored in a temporary storage in.
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.
Intro to OOP with Java, C. Thomas Wu Numerical Data
Data Conversion & Scanner Class
Multiple variables can be created in one declaration
Primitive and Reference Data Values
Java Programming: From Problem Analysis to Program Design, 4e
Primitive and Reference Data Values
Pseudocode and Flowcharts
Lecture 3 Expressions Richard Gesick.
Chapter 2: Basic Elements of Java
Fundamentals 2.
CS2011 Introduction to Programming I Elementary Programming
Data Types and Expressions
Data Types and Expressions
Data Types and Expressions
Presentation transcript:

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 3 Console Output Keyboard Input Numerical Data

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Standard Output Using System.out, we can output text to the console. System.out is an object that belongs to the PrintStream class PrintStream has two useful methods –print( someText) prints the given text to the console –println( someText) prints the text followed by a newline character the next output will appear on a new line

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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 data in a more useful format, we use the Scanner class (from Java 5.0). import java.util.Scanner; … Scanner scanner; scanner = new Scanner( System.in); String word = scanner.next (); String line = scanner.nextLine ();

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Numeric Data and Operations It is common to use computers for numeric calculations What do we need? –arithmetic operations –negation –functions like square root, sin, cos, log, … Java has a class called Math which provides the commonly used functions Math is in the lang package so no import is needed %Modulo /Division *Multiplication -Subtraction +Addition SymbolOperation

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Arithmetic Examples Most operators work as you would expect > > > > > > * 9 -> * 1.2 -> * 0.7 -> / 4 -> 0.9 Integer division is different –Result of an integer division is a whole number value –Any remainder is thrown away 10 / 4 -> 2 2 / 3 -> 0 Modulo operation gives the remainder from an integer division 10 % 4 -> 2 2 % 3 -> 2

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Arithmetic Expression What happens with the following expressions? * 4 Does it matter? We need two sets of rules for determining the order in which an expression gets evaluated Precedence Rules Associativity Rules

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Precedence and Associativity For different operators, precedence rules determine which operation gets done first. –Arithmetic operators are divided into three precedence levels unary - (negation) is done first * / % are evaluated first + - are evaluated next We can use () around parts of an expression to change the order of evaluation For operators of the same precedence, associativity rules control the order of evaluation. –Most operators are evaluated from left to right.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Variables A program that always used the same numbers wouldn't be very useful A variable is used in a program to store data that can be changed –A variable has a Java identifier for a name. In the last chapter, we declared variables whose location stored the address of an object Now we need to learn to declare variables to store numeric data.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Types for Numbers Numbers can be either whole numbers (integers) or real numbers (numbers with a decimal point). Java has six numeric types –byte, short, int, long are used for whole numbers –float, double are used for real numbers Different types store handle different ranges of values Most commonly, use int and double

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Variables 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. Sample variable declarations int i, j, k; float numberOne, numberTwo; long bigInteger; double bigNumber;

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Storing a value in a variable We assign a value to a variable using an assignment statements. The syntax is = ; The semantics (meaning) is –Evaluate the expression on the right –Store the result in the variable on the left Examples: sum = firstNumber + secondNumber; avg = (one + two + three) / 3.0;

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Primitive vs. Reference Numerical data are called primitive data types. –Contents are actual value of variable Objects are called reference data types, because the contents are addresses that refer to memory locations where the objects are actually stored.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Review: Assigning Objects customer A. A. The variable is allocated in memory. Customer customer; customer = new Customer( ); B. customer B. The reference to the new object is assigned to customer. Custo mer C. customer. C. The reference to another object overwrites the reference in customer. Custo mer A. A. Variables are allocated in memory. clemens twain B. clemens B. The reference to the new object is assigned to clemens. Custo mer C. clemens customer. C. The reference in clemens is assigned to customer. Customer clemens, twain; clemens = new Customer( ); twain = clemens;

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Assigning Numbers int firstNumber, secondNumber; firstNumber = 234; secondNumber = 87; A B firstNumber secondNumber A. A. Variables are allocated in memory. B. B. Values are assigned to variables int number; number = 237; A B C number = 35; number A. A. The variable is allocated in memory. B. 237 number B. The value 237 is assigned to number. 237 C C. The value 35 overwrites the previous value

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Overloaded Operator + The plus operator + can mean two different operations, depending on the context. + is an addition if both are numbers. If either one of them is a String, the it is a concatenation. Evaluation goes from left to right. output = “test” ; output = “test”;

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Using Scanner with Numbers When we use the next and nextLine methods of a Scanner, what we get is a String To do numeric calculations, we need numbers –Convert a String to a number using parse methods of classes that represent different kinds of numbers –The Scanner class has methods that allow you to read a number directly

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Wrapper classes For each primitive type, there is an associated class Each of these classes has a method for converting a String to the associated numeric type String numStr = kbd.next(); int num = Integer.parseInt( numStr); parseDoubleDoubledouble parseIntIntegerint parse MethodWrapper ClassPrimitive Type

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter MethodExample 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(); nextLine()String line = scanner.nextLine(); Scanner Methods:

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Formatting Numbers The DecimalFormat class allows you to control how many digits appear after the decimal place when you print floating point numbers DecimalFormat formatter = new DecimalFormat( "0.00"); The NumberFormat class allows you to create formatters for currency and percentages NumberFormat formatter = NumberFormat.getCurrencyInstance(); NumberFormat formatter = NumberFormat.getPercentInstance(); Both classes have a format method which returns the formatted String System.out.println( formatter.format( variable));

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Mixing Types in Expressions If x is a double and y is an int, what will be the data type of the following expression? x * y The answer is double. The data types of the operands in mixed expressions are converted based on the promotion rules. 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. byte -> short -> int -> long -> float -> double

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Explicit Type Casting Instead of relying on the promotion rules, we can make an explicit type cast by prefixing the operand with the data type using the following syntax: ( ) Example (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.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Implicit Type Casting Consider the following expression: double x = 3 + 5; The result of is of type int. However, since the variable x is double, the value 8 (type int) is promoted to 8.0 (type double) before being assigned to x. Notice that it is a promotion. Demotion is not allowed. int x = 3.5; A higher precision value cannot be assigned to a lower precision variable.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Some Math Class Methods The sine of a. (Note: all trigonometric functions are computed in radians) sin(a) The square root of a. sqrt(a) The larger of a and b. max(a,b) Natural logarithm (base e) of a. log(a) The number a raised to the power of b. pow(a,b) Natural number e raised to the power of a. exp(a) The largest whole number less than or equal to a. floor(a) DescriptionMethod Table 3.8 page 113 in the textbook contains a list of class methods defined in the Math class.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Random Number Generation The method Math.random is called a pseudorandom number generator and returns a number of type double that is greater than or equal to 0.0 but less than 1.0. If we want to generate random integers, we must scale the result to make it fall within the desired range. To get integers from min to max, use the formula: y = (int)(Math.random() * (max – min + 1) + min)

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Incremental Development It is much easier to get a program working if you develop it in small steps. As you design the program, think about the order that things need to be done –Some parts depend on other parts. Many programs can be broken up into three main parts –Read the input values –Do some computation –Print the results Test each step before you go on to the next.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Practice Development Newton's Law of Gravitation –F = k M 1 M 2 / d 2 –where k = 6.67E-8 dyne-cm 2 /g 2 –M 1, M 2 are the masses of two bodies (in g) –d is the distance between the bodies (in cm) –F is the gravitational force between the bodies (in dyne) Write an application that –Accepts the masses of two bodies and the distance between them (in cm) –Computes the force between the bodies –Prints out the data and the results in a nice readable format