Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 3 - 1 Chapter 3 Console Output Keyboard Input Numerical."— Presentation transcript:

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

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

3 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 3 - 3 Special Characters There are some characters that can't be put into a String just by typing them –The backslash (\) character is an escape charactre which indicates that the character after it needs to be handled differently than usual. to put a \ into a String\\ to put a double quote in a String \" tab\t newline\n MeaningCharacter Representati on

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

5 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 3 - 5 Data Types We've seen several examples of class data types –String, Date, SimpleDateFormat, Scanner Computers are often used for numerical calculations –We need some data types for numeric data Java provides a number of numerical types We'll see that numeric types are different than class types in a number of ways

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

7 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 3 - 7 Arithmetic Examples Most operators work as you would expect 2 + 3 -> 5 1.2 + 3.4 -> 4.6 5.6 + 7 -> 12.6 3.4 - 1.2 -> 2.2 9 - 6 -> 3 5 - 2.5 -> 2.5 8 * 9 -> 72 1.2 * 1.2 -> 1.44 2 * 0.7 -> 1.4 3.6 / 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

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

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

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

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

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

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

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

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

16 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 3 - 16 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. 234 87 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. 35 237. C. The value 35 overwrites the previous value 237. 35

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

18 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 3 - 18 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” + 1 + 2; output = 1 + 2 + “test”;

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

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

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

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

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

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

25 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 3 - 25 Implicit Type Casting Consider the following expression: double x = 3 + 5; The result of 3 + 5 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.

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

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

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

29 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 3 - 29 Exercise Suppose that you have been given a time in seconds and you want to convert that to some number of hours, minutes and seconds.

30 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 3 - 30 For next time Think about your TV as an object. –What properties does it have? –What messages do you send to it using the remote control? What kinds of objects do you interact with in the real world? –List 2-3 objects and suggest some properties and behavior that are associated with each.


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

Similar presentations


Ads by Google