1 / 46

Chapter 4

Chapter 4. Performing Calculations and Formatting Numbers. 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.

pbeach
Download Presentation

Chapter 4

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 4 Performing Calculations and Formatting Numbers

  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.

  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.

  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.

  5. Arithmetic Operators

  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: fltResult = fltValue/intCount; this statement has mixed data types but Java will allow it because the result is float data type. • If you assigned to intResult instead of fltResult than it would be an invalid calculation. Java won’t allow it.

  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 intMinutes = 90: • intHours = intMinutes/60; and intMinutes = intMinutes%60;

  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.

  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.

  10. Math.pow(double Number, double Power) The pow Method—General Format

  11. dblFiveSquared = Math.pow(5.0, 2.0); The pow Method—Example

  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 : fltTotal += fltPay;. • This is the same as fltTotal = fltTotal + fltPay;. • The assignment operators have the lowest precedence than the binary operators.

  13. Increment and Decrement Operators • There are increment operators ++ and decrement operators -- • If we wish to increment one by you would write the statement: • intCount = intCount + 1 or intCount += 1 or use the increment operator intCount++ • Increment operator placed before the variable is known as prefix operation and placed after is known as a postfix operation.

  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.

  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.

  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.

  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.

  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.

  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 : fltValue = (float) intTotal / (float) intUnit;

  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 : 1st way : fltValue = Float.parseFloat(strEntered); • This statement is for Java 1.2 version and above. • The 1st way only works for browsers that support Java 1.2 and above. • For example: 2nd way : fltValue = Float.valueOf(strEntered).floatValue();

  21. Converting String to Numeric Data Types Continued • This statement is supported by Java1.1 version and above. • The 2nd way works for all browsers now that support Java1.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.

  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 BigDecimal class in the java.math package.

  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 valueOf method throws an exception. • It will also throw an exception if the user enters a decimal value for a field that should be integer.

  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: lblOutput.setText(“” + fltPay); or • lblOutput.setText(“Pay : ” + fltPay); • The second way is an explicit conversion using the valueOf method from the String class. • For example:lblOutput.setText(String.valueOf(fltPay));

  25. Formatting Numeric Output • Many countries have different formatting rules for displaying numbers and operating system stores the rules for formatting as a locale. • You can retrieve the formatting specifications for a locale using subclasses of the NumberFormat 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.

  26. The Instance Methods • You must include the package, import java.text.*; , if you wish to use the NumberFormat class. • You must create an object of the Number format class for which formatting you want.

  27. Decimal Numbers • You set the number of decimal positions you want the value to display. • With setMaximumFractionDigits 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: • fmtDecimal.setMaximumFractionDigits(2); • fmtDecimal.setMiniimumFractionDigits(2);

  28. Decimal Numbers Continued • For example : strNumber = fmtDecimal.format(fltValue); • Then it can be displayed as lblOutput.setText(strNumber); • Besides setting the number of decimal positions, you can also set the number of Integer positions by setMaximumIntegerDigits and setMinimumIntegerDigits methods.

  29. Currency Formats • The getCurrencyInstance 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.

  30. Percent Formats • The getPercentInstance 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.

  31. Selected Methods of the NumberFormat Class

  32. Selected Methods of the NumberFormat Class Continued

  33. Specifying a Locale • You can force your application to use a specific style of formatting by specifying the locale in the getInstance method using the Locale object. • For example: You can force a formatting adapted by France by: • NumberFormat fmtDecimal = NumberFormat.getInstance(Locale.FRENCH); • You can also retrieve a list of available locales on the current system using the getAvailableLocales method.

  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.

  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.

  36. try { // The statement(s) that might generate an exception. } catch(ErrorObject errIdentifier) { // The statement(s) to handle the exception. } The try and catch—General Format

  37. try { //Integer division. Zero for intSecond throws an exception. intResult = intFirst / intSecond; lblIntegerResult.setText("" + intResult); } catch(ArithmeticException err) { showStatus("Error in calculation"); } The try and catch—Example

  38. Common Exception Objects

  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.

  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.

  41. 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 The Float Class—Constructors

  42. Float FltRate = new Float(txtRate.getText()); //Convert string to float Float FltHours = new Float(txtHours.getText()); Float FltTotal = new Float(0.0f); The Float Class—Examples

  43. Some of the Methods in the Integer Class and Float Class

  44. Partial List of Float Methods

  45. Integer(int) Integer(String) Integer Class—Constructors

  46. Integer IntQuantity = new Integer(txtQuantity.getText()); Integer IntCount = new Integer(0); Integer Class—Examples

More Related