Programming with Java 1 Chapter 4 Performing Calculations














































- Slides: 46

Programming with Java 1 Chapter 4 Performing Calculations and Formatting Numbers © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 2 Objectives • Perform calculations using the arithmetic operators. • Calculate and assign the result using the assignment operators. • Add and subtract using the increment and decrement operators. • Perform multiple calculations correctly based on the precedence of operators. • Retrieve string data from the screen and convert to numeric for calculations. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 3 Objectives Continued • Convert between data types both implicitly and explicitly. • Find the formatting rules for the locale where an applet is run. • Format output for currency, percent or decimal numbers. • Catch input and calculation errors by using exception handling. • Declare variables based on the numeric wrapper classes and perform operations using the methods of the classes. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 4 Calculation Operators • The common arithmetic operators perform basic calculations. • Then there is the increment and decrement operators. • The shortcut notation and also the modulus. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 5 Arithmetic Operators Arithmetic Operator + Purpose – Subtraction * Multiplication / Division % Modulus (remainder) Addition © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 6 Arithmetic Operators • In Java, = sign does not mean equality but it means assignment. • Java is more strict about data types than most programming languages. • If you mix datatypes then you must be careful. • For example: flt. Result = flt. Value/int. Count; this statement has mixed data types but Java will allow it because the result is float data type. • If you assigned to int. Result instead of flt. Result than it would be an invalid calculation. Java won’t allow it. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 7 Modulus • Modulus is the remainder of a division. • The modulus is sometimes very important such as calculations for hours and minutes. • For example, the decimal value for the hours does not help to know the minutes. • Conversion of minutes into hours and minutes, look at the calculation, if int. Minutes = 90: • int. Hours = int. Minutes/60; and int. Minutes = int. Minutes%60; © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 8 The Order of Arithmetic Operations • The order of precedence is very important and it is as follows: parentheses – the highest, then it is exponent, then it is multiplication, division and modulus (equal in precedence), then it is addition and subtraction. • The operation is read left to right. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 9 Exponentiation • There is no operator for exponentiation. • There are 2 ways to raise a number to the power: • One by simple multiplication. • The other by using the pow method which is found in the java. math package. • The pow method requires double precision floating point arguments. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 10 The pow Method—General Format Math. pow(double Number, double Power) © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 11 The pow Method—Example dbl. Five. Squared = Math. pow(5. 0, 2. 0); © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 12 Assignment Operators • In addition to the equal sign there are other assignment operators that perform a calculation and assign the result at the same time. • They are handy for accumulating totals and counts. • For example : flt. Total += flt. Pay; . • This is the same as flt. Total = flt. Total + flt. Pay; . • The assignment operators have the lowest precedence than the binary operators. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 13 Increment and Decrement Operators • There are increment operators ++ and decrement operators -- • If we wish to increment one by you would write the statement: int. Count = int. Count + 1 or int. Count += 1 or use the increment operator int. Count++ • Increment operator placed before the variable is known as prefix operation and placed after is known as a postfix operation. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 14 Increment and Decrement Operators Continued • • Increment, Decrement operators have precedence over binary operators and they are read right to left. Prefix operation the variable is incremented before the statement is executed. Postfix operation the variable is incremented after the statement is executed. Decrement operator is similar to the increment operator with its prefix and postfix operations. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 15 Converting between Data Types • In other programming languages there is an automatic conversion between the data types but not in Java. • In Java, the compiler check the data type for all operands and arguments and insists on the correct data type. • When calculating with mixed numeric data types some operands may be implicitly converted or “promoted” so that precision is maintained. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 16 Implicit Numeric Type Conversion • Java tries to maintain the greatest precision possible. • This is needed when you have mixed data types but the result data type has to have the higher precision for the implicit conversion otherwise you will have an error. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 17 Implicit Numeric Type Conversion Continued • The implicit conversions are as follows: • If both operands are one of the integer types (byte, short, int, or long) and one of the operands is long, the Java compiler converts the other operand to long and the result of the calculation is long. • If both operands are one of the floating point types (float or double) and one of the operands is double, Java converts the other operand to double and the result of the calculation is double. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 18 Implicit Numeric Type Conversion Continued • If one operand is an integer type and one is long, the integer is converted to long and the result of the calculation is long. • If one operand is an integer type and one is float, the integer is converted to float and the result of the calculation is float. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 19 Explicit Conversion • You can convert from one numeric data type to another by casting. • To create a cast operator, you put the primitive data type in parentheses before the variable. • This converts the data type for calculation into a new variable but does not convert the original variable’s data type. • For example : flt. Value = (float) int. Total / (float) int. Unit; © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 20 Converting String to Numeric Data Types • Java does not automatically convert strings to numeric data types. • There are two ways to convert strings to numeric data types. • For example : 1 st way : flt. Value = Float. parse. Float(str. Entered); • This statement is for Java 1. 2 version and above. • The 1 st way only works for browsers that support Java 1. 2 and above. • For example: 2 nd way : flt. Value = Float. value. Of(str. Entered). float. Value(); © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 21 Converting String to Numeric Data Types Continued • This statement is supported by Java 1. 1 version and above. • The 2 nd way works for all browsers now that support Java 1. 1 version. • You will notice that for both ways you are using the wrapper class Float to convert a string to primitive data type float. • There are other classes such as Double, Integer, and Long. These are some of the numeric “wrapper” classes. • You can use them in the same way as the example above replacing with numeric data type you want. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 22 Accuracy of Decimal Fractions • • • When you display decimal fractions, you will find the outcome inaccurate, even if it is for the fraction 1/10. You probably will get 0. 0098 which close to 0. 1 but not accurate. The reason for this is that floating point values are stored as binary digits and an exponent (which can store very large numbers or very small) rather than decimal digits. Different versions of JVM and different browsers produce slightly different results. But if you need to keep accurate decimal fractions, such as for dollars and cents, you will have to use the Big. Decimal class in the java. math package. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 23 Invalid Data Entry • What happens if the user enter text instead of a value, or leaves the textfield blank and you try and convert it to a particular numeric data type. • The value. Of method throws an exception. • It will also throw an exception if the user enters a decimal value for a field that should be integer. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 24 Converting Numeric fields to String • There are two ways to convert numeric to text. • One way is an implicit conversion : by concatenation of numeric field to string (or empty string). • For example: • lbl. Output. set. Text(“” + flt. Pay); or lbl. Output. set. Text(“Pay : ” + flt. Pay); • The second way is an explicit conversion using the value. Of method from the String class. • For example: lbl. Output. set. Text(String. value. Of(flt. Pay)); © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 25 Formatting Numeric Output • Many countries have different formatting rules for displaying numbers and operating system stores the rules formatting as a locale. • You can retrieve the formatting specifications for a locale using subclasses of the Number. Format class, which comes from the text package. • The formatting classes allow you to format general numbers, currency, and percent fields. • You can also specify the number of decimal places to display. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 26 The Instance Methods • You must include the package, import java. text. *; , if you wish to use the Number. Format class. • You must create an object of the Number format class for which formatting you want. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 27 Decimal Numbers • • • You set the number of decimal positions you want the value to display. With set. Maximum. Fraction. Digits method, the numbers are automatically rounded to the maximum number of digits. DO NOT forget to set the minimum because if the numbers are less than the maximum decimal positions it will not round up to the maximum. For example if the maximum decimal position is set to 2 and the minimum decimal position is not set and the value is 1 it will not display 1. 00, it will only display 1. So to achieve for example 2 decimal places, you will have to: fmt. Decimal. set. Maximum. Fraction. Digits(2); fmt. Decimal. set. Miniimum. Fraction. Digits(2); © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 28 Decimal Numbers Continued • For example : str. Number = fmt. Decimal. format(flt. Value); • Then it can be displayed as lbl. Output. set. Text(str. Number); • Besides setting the number of decimal positions, you can also set the number of Integer positions by set. Maximum. Integer. Digits and set. Minimum. Integer. Digits methods. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 29 Currency Formats • The get. Currency. Instance method retrieves the local format for currency numbers. • Fractional values are rounded to fit the format so you don’t have to set the maximum and minimum fraction digits. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 30 Percent Formats • The get. Percent. Instance method to retrieve the local percent format. • The format method converts the argument to a percent and formats it with a percent sign. • You can set the minimum and maximum fraction digits. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 31 Selected Methods of the Number. Format Class Method Purpose format Return a string that holds the formatted number. get. Instance Return the default number format for the current locale. get. Currency. Instance Return the currency format for the current locale. get. Number. Instance Return the general-purpose number format for the current locale. get. Percent. Instance Return the percent number format for the current locale. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 32 Selected Methods of the Number. Format Class Continued get. Scientific. Instance Return the scientific number format for the current locale. get. Available. Locales Return an array of available locales on the current system. parse Return a number from a formatted string. set. Maximum. Fraction. Digits Set the maximum number of digits to the right of the decimal point. set. Maximum. Integer. Digits Set the maximum number of digits to the left of the decimal point. set. Minimum. Fraction. Digits Set the minimum number of digits to the right of the decimal point. set. Minimum. Integer. Digits Set the minimum number of digits to the left of the decimal point. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 33 Specifying a Locale • You can force your application to use a specific style of formatting by specifying the locale in the get. Instance method using the Locale object. • For example: You can force a formatting adapted by France by: Number. Format fmt. Decimal = Number. Format. get. Instance(Locale. FRENCH); • You can also retrieve a list of available locales on the current system using the get. Available. Locales method. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 34 Handling Exceptions • When user inputs data and enters the data wrong such as: • Leaving the textfield blank and trying to convert to numeric. • The textfield has a floating point value and then you try to convert it to an integer. • The user enters zero and you try and divide by zero. • All the above situations generate an Exception object. • The correct terminology is “throws an exception” and it is your job to “catch” the exception. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 35 Try and Catch • The statement(s) that might cause the error go in the try block ({}). • There is always a catch block associated with a try block. • If the try block executes successfully, then it will skip the catch block. • If the try block does not execute successfully, then it will directly jump to the catch block skipping any statements in the try block. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 36 The try and catch—General Format try { // The statement(s) that might generate an exception. } catch(Error. Object err. Identifier) { // The statement(s) to handle the exception. } © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 37 The try and catch—Example try { //Integer division. Zero for int. Second throws an exception. int. Result = int. First / int. Second; lbl. Integer. Result. set. Text("" + int. Result); } catch(Arithmetic. Exception err) { show. Status("Error in calculation"); } © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 38 Common Exception Objects Exception Object Purpose Arithmetic. Exception Error caused by a calculation, such as division by zero. Number. Format. Exception Problem converting a string to a number; occurs when the text field is blank or contains a fraction when an integer is required. Illegal. Argument. Exception Unable to format the value passed to one of the format methods. File. Not. Found. Exception File does not exist in path specified. IOException Failure of an input or output operation such as reading from a file. Out. Of. Memory. Exception Not enough memory to create an object. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 39 Unhandled Exceptions • What happens if you have an exception and you don’t handle. • It is passed up a level and if it is not handled there, it passed up again, until it reaches the top of the program, and it may display an error message. • But in an applet, often it will just sit there with no message or anything to indicate there is a problem. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 40 Using the Wrapper Data Classes • Each of the primitive data types has a wrapper class that you can use. • Each of the data classes have methods that you can use which conforms closer to object-oriented programming. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 41 The Float Class—Constructors Float(double) //Create a Float instance converting the double value Float(float) //Create a Float instance converting the float value Float(String) //Create a Float instance converting the string value © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 42 The Float Class—Examples Float Flt. Rate = new Float(txt. Rate. get. Text()); //Convert string to float Flt. Hours = new Float(txt. Hours. get. Text()); Float Flt. Total = new Float(0. 0 f); © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 43 Some of the Methods in the Integer Class and Float Class © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 44 Partial List of Float Methods Method Purpose int. Value Returns the value of the Float as an integer. long. Value Returns the value of the Float as a long integer. float. Value Returns the value of the Float as a float. double. Value Returns the value of the Float as a double. to. String Converts the float value to String. is. Infinite Returns true if the Float value is infinity. is. Na. N Returns true if the Float value is not a number. © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 45 Integer Class—Constructors Integer(int) Integer(String) © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.

Programming with Java 46 Integer Class—Examples Integer Int. Quantity = new Integer(txt. Quantity. get. Text()); Integer Int. Count = new Integer(0); © 2002 The Mc. Graw-Hill Companies, Inc. All rights reserved.