You are on page 1of 14

19133 Electronic Processing Systems

2005-06

Page 3_1

Section 3 More with Numbers and Operations and mathematical Functions in Java
Changing from One type of number to another. Casting.
There are times in our program when we want to change the type of a value stored in a variable in our program. For example we may wish to take a floating point value and only deal with the integer part of the number. Another example is when we want to divide one integer by another but want to get a floating point result. One mechanism that we can use to do this is known as casting. If we want to cast one type of number into another we use the name of the type we want the number to become before the number or variable within brackets. For example myInt=(int)myDouble; Converts the contents of myDouble to an integer. If the variable myDouble contained the value 37.34528 after this statement had been executed myInt would contain the value 37. To convert from an integer to a double. myDouble=1/(double)myInt The code above finds the reciprocal value of the contents of an integer variable. Before we can perform the division we need to convert the divisor into a floating point number to insure that a floating point division occurs. The following class shows how we can use casting to convert a double into an integer value. The program is designed to allow the user to enter a sum of money. The program then calculates the minimum number of notes and coins required for this amount of money.
public class MakeChange { public static void main(String[] args) { //-----------------Variables for Calculation-----------------double money; int pounds; int pennies; int residual; //-----------------Variables for Results-----------------int twenties; int tenners; int fivers; int twoPoundCoins; int poundCoins; int fiftyPCoins; int twentyPCoins; int tenPCoins; int fivePCoins; int twoPCoins; int onePCoins;

19133 Electronic Processing Systems

2005-06

Page 3_2

//----------------------------------Get Input from User----------------------------String instr=JOptionPane.showInputDialog(null, "Please input a sum of money", "Change maker", JOptionPane.QUESTION_MESSAGE); money=Double.parseDouble(instr); //---------------------------Find number of pounds and pennies-------------------pennies=(int)(money*100); pounds=pennies/100; pennies=pennies%100; //-----------------------------Confirmation message--------------------(1) Use of Casting String outstr="You entered "+ pounds+" pounds\n and " +pennies+" pennies"; JOptionPane.showMessageDialog(null, outstr, "Your Change", JOptionPane.INFORMATION_MESSAGE); //=============Divide pounds into notes and coins============== twenties=pounds/20; residual=pounds%20; tenners=residual/10; residual=residual%10; fivers=residual/5; residual=residual%5; twoPoundCoins=residual/2; poundCoins=residual%2; fiftyPCoins=pennies/50; residual=pennies%50; twentyPCoins=residual/20; residual=residual%20; tenPCoins=residual/10; residual=residual%10; fivePCoins=residual/5; residual=residual%5; twoPCoins=residual/2; onePCoins=residual%2;

(2) Use of integer division and modulus operators

19133 Electronic Processing Systems

2005-06

Page 3_3

//============= create output string===================== String outstr1="You have:\n \t"+ twenties +"\t 20 pounds notes\n" +"\t" + tenners +"\t 10 pound notes\n" +"\t" + fivers +"\t 5 pound notes\n" +"\t" + twoPoundCoins +"\t 2 pound coins\n" +"\t" + poundCoins +"\t 1 pound coins\n" +"\t" + fiftyPCoins +"\t 50 p coins\n" +"\t" + twentyPCoins +"\t 20 p coins\n" +"\t" + tenPCoins +"\t 10 p coins\n" +"\t" + fivePCoins +"\t 5 p coins\n" +"\t" + twoPCoins +"\t 2 p coins\n" +"\t" + onePCoins +"\t 1 p coins\n"; System.out.print(outstr1); System.exit(0); } }

(3) use of formatting characters in strings

In this program there are three key ideas,


1. Casting of variables, 2. Use of the integer division and modulus operators 3. Use of formatting characters in strings. We will discuss each of these in turn The first problem we have in our program is splitting a single floating point number which contains the sum of money we are working with into two integer numbers one being the number of pounds in the sum of money, the other representing the number of pence. I have assumed that a floating point number in the form of XXX.YY is going to be enetered, the number on the left of the decimal point representing pounds the two digits to the right of the decimal point representing the pence. The code to do this works as follows: pennies=(int)(money*100); pounds=pennies/100; pennies=pennies%100; The value in the floating point variable money is multiplied by 100. This changes a number like 23.45 representing 23 pounds and 45 pence to the number 2345.0, giving us the money in pennies. We then cast the number into an integer. (2345.0 becomes 2345) This allows us to perform integer division and modulus operations using 100. By performing the division by 100 we get an integer value representing the number of pounds entered (2345/100=23) By performing the modulus operation with 100 we get an integer number representing the number of pennies (2345%100=45).

19133 Electronic Processing Systems

2005-06

Page 3_4

The second problem we have in our code is working out the coins and notes that we require for the sum of money entered. The code to do this works as follows . Assume that we are dealing with 238 pounds twenties=pounds/20; residual=pounds%20; tenners=residual/10; residual=residual%10; fivers=residual/5; residual=residual%5; twoPoundCoins=residual/2; We perform integer division on the variable containing our total number of pounds by the value of our largest bank note. In this case a twenty pound note. The result of this operation gives the largest number of 20 pound notes that results in a sum less than the total amount of money. (238/20=11). We know that we need 11 twenty pound notes. We then perform a modulus operation on the number of pounds using 20. This gives the remainder of the money that is not accounted for in twenty pound notes. (238%20=18). This value is stored in the variable residual.

We now perform integer division on the contents of residual with our next largest bank note. The result of 18/10=1 indicates that we need 1 ten pound note. The modulus of residual is then taken with 10 (18%10=8). poundCoins=residual%2; And is stored in residual. This indicates that we have 8 pounds unallocated. The process is continued until we determine the breakdown of notes and coins required for the original number of pounds. A similar process is used to determine the coins needed for the pence in our sum of money. The third problem we have is to output our data. We are dealing with a list of values here and it would be good to format our output neatly. Java strings can included characters that are not printed, but control the format with which the string is printed. These characters are indicated by the fact that they are proceeded by a backslash character \. In this example I am using to non printing characters. \n which causes a new line character to be printed and \t which causes a spacing tab to be printed. This allows me to build up an output string that will allow me to tabulate the results of the calculation. I have spread the concatenation of the string over several lines to make it easier for me to set up the formatting for the string. String outstr1="You have:\n \t"+ twenties +"\t 20 pounds notes\n" +"\t" + tenners +"\t 10 pound notes\n" +"\t" + fivers +"\t 5 pound notes\n" +"\t" + twoPoundCoins +"\t 2 pound coins\n" +"\t" + poundCoins +"\t 1 pound coins\n" +"\t" + fiftyPCoins +"\t 50 p coins\n" +"\t" + twentyPCoins +"\t 20 p coins\n" +"\t" + tenPCoins +"\t 10 p coins\n" +"\t" + fivePCoins +"\t 5 p coins\n" +"\t" + twoPCoins +"\t 2 p coins\n" +"\t" + onePCoins +"\t 1 p coins\n";

19133 Electronic Processing Systems

2005-06

Page 3_5

The output produced by the program in the console window looks like:
You have: 11 1 1 1 1 0 2 0 1 0 0

20 pounds notes 10 pound notes 5 pound notes 2 pound coins 1 pound coins 50 p coins 20 p coins 10 p coins 5 p coins 2 p coins 1 p coins

Exercise 3.1 Create a new workspace for lesson3 in your diskspace then set up a java project containing the makeChange class shown above and check that it works correctly and you understand how it operates. Remember that you will have to include the import of the javax.swing.JOptionMessage before the start of your class.

Using short cut arithmetic operators.


Many lines in the program above take the form of residual=residual%10; This line is effectively saying take the contents of the integer variable residual, divide them by the integer 10 and store the result in the variable residual.

In programming we frequently see statements like this where the new contents of the variable depend on the original contents with some operation performed on them. Java provides short cut operators to save you having to use the variable name twice. The short cut operators are: Symbol Example += Result+=value; -= Result-=value; *= Result*=value; /= Result/=value; %= Result%=value; Effect of operation Result contains original contents plus value Result contains original contents minus value Result contains original contents times value Result contains original contents divided by value Result contains the modulus of its original contents using value

19133 Electronic Processing Systems

2005-06

Page 3_6

We could modify the code we wrote above to use the %= shortcut operator and it would look like: twenties=pounds/20; residual=pounds%20; tenners=residual/10; residual %=10; fivers=residual/5; residual %= 5; twoPoundCoins=residual/2 poundCoins=residual%2; Exercise 3.2 Modify the make the makeChange class you wrote in Exercise 3.1 to use short cut operators were appropriate and check that it works correctly. In this particular case there is no great advantage in using the short cut operations. In fact it makes the coode slightly more difficult to read. However in certain situations using the operators will make your code shorter and less likely to suffer from typing errors.

Mathematical operations in Java.


Java includes a class called Math which contains methods to perform the most common mathematical operations that you are likely to meet. To use these methods we must pass data to them as parameters. This data can either be a literal value or be stored in a variable. The type of the data must be appropriate to the parameter type. These methods return a value when they are called and we must do something with it. Therefore we must either: Assign the return value to a variable. Pass it as a parameter to another method Concatenate the return value into a string We access these methods by using a format:

Name of Class in this case Math myVariable= Math.Methodname(parameters) Variable to store data returned Name of method

19133 Electronic Processing Systems

2005-06

Page 3_7

The basic methods in math can be defined into the following groups Numeric Methods Name Method Purpose abs Returns the absolute value of parameter signum max min floor ceil round rint random Returns -1 if number negative 0 if number 0 +1 if number positive Returns the larger of two numbers Returns the smaller of two numbers Returns a double containing the integer value immediately more negative than parameter Returns a double containing the integer value immediately more positive than parameter Returns an integer containing the rounded value of parameter Returns a double containing integer value closest to parameter Returns a random float in the range of 0 to 1 Parameter Type double, float, long , int double or float double, float, long , int double, float, long , int double double double or float double No parameter Return Type Matches type of parameter passed to method Matches type of parameter passed to method Matches type of parameter passed to method Matches type of parameter passed to method double double long if passed double int if passed float double double

Powers and Logarithmic functions Name Method Purpose pow Raises the first parameter passed to the power of the second exp Exponential Raises e to the power of parameter expm1 Calculates (e x 1) where x is parameter passed sqrt Returns the square root of parameter cbrt Returns the cube root of parameter log Returns logarithm of parameter to base e log10 Returns logarithm of parameter to base 10 log1p Calculates ln( x + 1) where x is parameter passed

Parameter Type Passed two doubles double double double double double double double

Return Type double double double double double double double double

19133 Electronic Processing Systems Trignometric Functions Name cos

2005-06

Page 3_8

Method Purpose Returns the cosine of the parameter (angle in radians) sin Returns the sine of the parameter (angle in radians) tan Returns the tangent of the parameter (angle in radians) acos Returns the inverse cosine of parameter range of ( 0.0 ) asin Returns the inverse sine range of ( 2 2 ) atan Returns the inverse tangent range of ( 2 2 ) toDegrees Converts an angle in radians to degrees toRadians Converts an angle in degrees to radians

Parameter Type double double double double double double double double

Return Type double double double double double double double double

Functions for dealing with polar coordinates and complex numbers. Name atan2 hypot Method Purpose Parameter Type Returns angle associated with a Two doubles polar coordinate for a pair of Cartesian coordinates Returns the hypotenuse of right Two doubles angled triangle given length of other two sides Return Type double double

Hyperbolic Functions Name cosh sinh tanh Method Purpose Returns hyperbolic cosine of parameter Returns hyperbolic sine of parameter Returns hyperbolic tangent of parameter Parameter Type double double double Return Type double double double

19133 Electronic Processing Systems

2005-06

Page 3_9

Programming Example
Lets look at how we use some of the trigonometric functions in a java program. If we know the length of two sides of a triangle and the angle between them we can use the cosine rule to calculate the length of the unknown side.
a 2 = b 2 + c 2 2bc cos( A) a = b 2 + c 2 2bc cos( A)

b A c

Lets implement this in a Java Program

Program design
The first thing that we need to think about is our variables. Start by thinking about our inputs We need to input the lengths of two sides of our triangle. So we need variables to store the data. Lengths tend to be continuously varying rather than discretely varying so we should use floating point numbers to store them. To ensure simplicity we will declare the variables to hold the lengths as doubles and give them the names bSide and cSide. We also need to input our angle, It will be a continuously varying value so we need a floating point variable to store it. Again use a double and give it the name AngA. Now think of our outputs At the end of our calculation we will need to output the length of the third side a, Therefore we need a floating point number to store this so use a double called aSide. We will use an message dialog to create our output. Now think how we are going to get our input into the program. We will use input dialogs, so we will need three strings to hold our input, Lets think about what we want our input dialogs to look like. Our title messages should be the same, perhaps Triangle Calculation Demo. We can use simple prompts on the input dialog for example : Enter the length of side b. We need to think of the units of our inputs. Lets follow SI principles for our side lengths and use metres. Therefore we should change our prompt message to Enter the length of side b in metres. We have a choice for the units that we are going to use for the angle, we could use radians or degrees. Radians would be simpler to use with the trignometric functions in Java, however humans are frequently more comfortable using degrees to define angles. So we will use degrees. We will therefore have to convert from degrees to radians in our calculation.

19133 Electronic Processing Systems

2005-06

Page 3_10

Now lets think of our calculation section of the program. There will be two stages. First we convert our angle from degrees to radians. AngA=Math.toRadians(AngA); Class Name Method Name

Note to get access to the toRadians method we need to use the format ClassName.MethodName; Then we calculate the length of the square of sideA aSide=(bSide*bSide)+(cSide*cSide)-(2*bSide*cSide*Math.cos(AngA)); Call to cos method of Math class We can then find the square root of the data held in our variable aSide. aSide=Math.sqrt(aSide); Call to sqrt method of Math class

Having gone through these design steps we can start to write our program

19133 Electronic Processing Systems

2005-06

Page 3_11

The main method of our program would look something like this :
public static void main(String[] args) { double bSide; double cSide; double AngA; double aSide; //====================Input Section===================== String inpStrB=JOptionPane.showInputDialog(null, "Enter length of side b in metres", "Triangle Calculation Demo", JOptionPane.QUESTION_MESSAGE); bSide=Double.parseDouble(inpStrB); String inpStrC=JOptionPane.showInputDialog(null,"Enter length of side c in metres", "Triangle Calculation Demo", JOptionPane.QUESTION_MESSAGE); cSide=Double.parseDouble(inpStrC); String inpStrA=JOptionPane.showInputDialog(null, "Enter angle between sides b and c in degrees", "Triangle Calculation Demo", JOptionPane.QUESTION_MESSAGE); AngA=Double.parseDouble(inpStrA); //=======================Perform Calculation======================== AngA=Math.toRadians(AngA); // convert angle to radians

aSide=(bSide*bSide)+(cSide*cSide)-(2*bSide*cSide*Math.cos(AngA)); // calculate the square of the side length using the cosine rule aSide=Math.sqrt(aSide); // find side a length using square root.

//======================Perform Output========================= String outStr="The triangle has sides of "+aSide+", "+bSide+" and "+cSide+" metres."; JOptionPane.showMessageDialog(null,outStr,"Triangle calculation demo", JOptionPane.INFORMATION_MESSAGE); System.exit(0); }

Exercise 3.3 Create a new project, with an appropriate name, and add a class, again with an appropriate name which has a main method. Add the code above to the main method, and test to see if your program behaves appropriately. Remember that you will have to include the import of the javax.swing.JOptionMessage before the start of your class.

19133 Electronic Processing Systems

2005-06

Page 3_12

Passing return value of a method as a parameter for another method


There are some things that we can do to make our program a little shorter: if you consider one of the input statements:
String inpStrB=JOptionPane.showInputDialog(null, "Enter length of side b in metres", "Triangle Calculation Demo", JOptionPane.QUESTION_MESSAGE); bSide=Double.parseDouble(inpStrB);

We are going through two steps: We first declare a string and assign it to the return variable provided by the JOptionPane.showInputDialog method. The next line takes the contents of the string variable and passes it as a parameter to the Double.parseDouble method. The program never uses the contents of the string again. Therefore it makes sense to combine the two lines into a single instruction:
bSide=Double.parseDouble(JOptionPane.showInputDialog(null,"Enter length of side b in metres", "Triangle Calculation Demo",JOptionPane.QUESTION_MESSAGE));

This statement looks a little complicated but actually is straightforward, The call to the showInputDialog method takes place within the parentheses associated with the Double.parseDouble method. This is where the parseDouble method would expect to see a parameter of type string. The compiler accepts this because it knows the showInputDialog method returns a string. The compiler executes the showInputDialog method, takes the string that it returns and passes it directly as a parameter to the parseDouble method. The double value that this method returns is assigned to the double bSide. Another change that we can make is concerned with the section of code where we calculate the length of side a of the triangle. In the code above we again perform this calculation in two steps.
aSide=(bSide*bSide)+(cSide*cSide)-(2*bSide*cSide*Math.cos(AngA)); // calculate the square of the side length using the cosine rule aSide=Math.sqrt(aSide); // find side a length using square root.

There can be advantages in breaking calculations into several stages. When you are debugging your program you can check that each stage of the calculation is being performed satisfactorily. This is not possible if your calculation is performed in a single very complicated line. It can be easier for somebody looking at your code to understand what is happening if they see a series of simple stages in the calculation. However in this case as the expression we are evaluating is relatively straightforward we can combine the two lines into a single expression.
aSide=Math.sqrt((bSide*bSide)+(cSide*cSide)-(2*bSide*cSide*Math.cos(AngA))); // calculates side length using the cosine rule

19133 Electronic Processing Systems

2005-06

Page 3_13

Here the compiler evaluates the expression within the Parentheses associated with the sqrt method, passes the resulting value as a parameter to the sqrt method, then executes the method. The value returned by the method is assigned to the variable aSide. Exercise 3.4 Modify your program to pass the return string of the JOptionPane.showMessageDialog directly to the Double.parseDouble method for your 3 input statements. Also modify your calculation section of the program as shown above. Test that your program works correctly. We can extend our program now that we have calculated the length of the third side of the triangle. The sine rule could be used to calculate the two unknown angles of the triangle, opposite sides b and c
a b b sin( A) = B = sin 1 sin( A) sin( B ) a

Exercise 3.5 Modify your program from exercise 3.4 so that it also calculates the two unknown angles in the triangle. Declare appropriately named variables and add a second showMessageDialog to output the values of the three angles in degrees. Test that your program works appropriately. A final addition to our program would be to calculate the area of the triangle. The area of the triangle is given by

a
h

b A

1 ch 2 h = b tan( A) Area =

where h the height of the triangle is given by

c
Exercise 3.6 Modify your program from exercise 3.4 so that it also calculates the area of the triangle. Declare appropriately named variables and add a third showMessageDialog to output the area of the triangle in square metres. Test that your program works appropriately.

19133 Electronic Processing Systems

2005-06

Page 3_14

Summary Exercise: Section 3.


In this space note the important things that you have learned in this section of the course. After you have completed this section discuss with a demonstrator