Download Chapter 4 Performing Calculations and Formatting Numbers

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Programming with Java
1
Chapter 4
Performing Calculations and
Formatting Numbers
© 2002 The McGraw-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 McGraw-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 McGraw-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 McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
5
Arithmetic Operators
Arithmetic
Operator
+
Purpose
–
Subtraction
*
Multiplication
/
Division
%
Modulus (remainder)
Addition
© 2002 The McGraw-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: 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.
© 2002 The McGraw-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 intMinutes = 90:
•
intHours = intMinutes/60; and intMinutes = intMinutes%60;
© 2002 The McGraw-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 McGraw-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 McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
10
The pow Method—General
Format
Math.pow(double Number, double Power)
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
11
The pow Method—Example
dblFiveSquared = Math.pow(5.0, 2.0);
© 2002 The McGraw-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 : fltTotal += fltPay;.
•
This is the same as fltTotal = fltTotal + fltPay;.
•
The assignment operators have the lowest precedence than the
binary operators.
© 2002 The McGraw-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:
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.
© 2002 The McGraw-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 McGraw-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 McGraw-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 McGraw-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 McGraw-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 McGraw-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 : fltValue = (float) intTotal / (float) intUnit;
© 2002 The McGraw-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 : 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();
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
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.
© 2002 The McGraw-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 BigDecimal class in
the java.math package.
© 2002 The McGraw-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 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.
© 2002 The McGraw-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:
•
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));
© 2002 The McGraw-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 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.
© 2002 The McGraw-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 NumberFormat class.
•
You must create an object of the Number format class for
which formatting you want.
© 2002 The McGraw-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 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);
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
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.
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
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.
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
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.
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
31
Selected Methods of the
NumberFormat Class
Method
Purpose
format
Return a string that holds the formatted number.
getInstance
Return the default number format for the current locale.
getCurrencyInstance
Return the currency format for the current locale.
getNumberInstance
Return the general-purpose number format for the current locale.
getPercentInstance
Return the percent number format for the current locale.
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
32
Selected Methods of the NumberFormat
Class Continued
getScientificInstance
Return the scientific number format for the current locale.
getAvailableLocales
Return an array of available locales on the current system.
parse
Return a number from a formatted string.
setMaximumFractionDigits
Set the maximum number of digits to the right of the decimal
point.
setMaximumIntegerDigits
Set the maximum number of digits to the left of the decimal
point.
setMinimumFractionDigits
Set the minimum number of digits to the right of the decimal
point.
setMinimumIntegerDigits
Set the minimum number of digits to the left of the decimal
point.
© 2002 The McGraw-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 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.
© 2002 The McGraw-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 McGraw-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 McGraw-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(ErrorObject errIdentifier)
{
// The statement(s) to handle the exception.
}
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
37
The try and catch—Example
try
{
//Integer division. Zero for intSecond throws an exception.
intResult = intFirst / intSecond;
lblIntegerResult.setText("" + intResult);
}
catch(ArithmeticException err)
{
showStatus("Error in calculation");
}
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
38
Common Exception Objects
Exception Object
Purpose
ArithmeticException
Error caused by a calculation, such as division by zero.
NumberFormatException
Problem converting a string to a number; occurs when the
text field is blank or contains a fraction when an integer is
required.
IllegalArgumentException
Unable to format the value passed to one of the format
methods.
FileNotFoundException
File does not exist in path specified.
IOException
Failure of an input or output operation such as reading
from a file.
OutOfMemoryException
Not enough memory to create an object.
© 2002 The McGraw-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 McGraw-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 McGraw-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 McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
42
The Float Class—Examples
Float FltRate = new Float(txtRate.getText()); //Convert string to float
Float FltHours = new Float(txtHours.getText());
Float FltTotal = new Float(0.0f);
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
43
Some of the Methods in the
Integer Class and Float Class
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
44
Partial List of Float Methods
Method
Purpose
intValue
Returns the value of the Float as an integer.
longValue
Returns the value of the Float as a long integer.
floatValue
Returns the value of the Float as a float.
doubleValue
Returns the value of the Float as a double.
toString
Converts the float value to String.
isInfinite
Returns true if the Float value is infinity.
isNaN
Returns true if the Float value is not a number.
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
45
Integer Class—Constructors
Integer(int)
Integer(String)
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
46
Integer Class—Examples
Integer IntQuantity = new Integer(txtQuantity.getText());
Integer IntCount = new Integer(0);
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.