Module 4: Numbers
A calculation example
Consider this example with numbers:
- First try the applet.
- Now, let's look at the source:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class InterestCalcApplet extends Applet implements ActionListener {
// Three text fields:
TextField principalField, rateField, numYearsField;
// Variables we will need:
double simpleInterest = 0;
double amount = 0;
double principal = 0;
double numYears = 0;
double rate = 0;
public void init()
{
// Create the textfields, labels and button.
principalField = new TextField (6);
rateField = new TextField (6);
numYearsField = new TextField (6);
Label principalLabel = new Label ("Principal ");
Label rateLabel = new Label ("Rate (%) ");
Label numYearsLabel = new Label ("Time (in years) ");
Button calcButton = new Button ("Calculate");
// Lay out the components.
add (principalLabel);
add (principalField);
add (rateLabel);
add (rateField);
add (numYearsLabel);
add (numYearsField);
add (calcButton);
// Add the applet as listener to the calc button so that
// actionPerformed (below) is called when the button is clicked.
calcButton.addActionListener (this);
}
public void actionPerformed (ActionEvent e)
{
// First, let's work with the principal. Start
// by getting the string from the textfield:
String principalString = principalField.getText ();
// Remove whitespace on either end:
principalString = principalString.trim ();
// Next, create a Double object:
Double principalDouble = new Double (principalString);
// Now extract the value and assign it to our double variable:
principal = principalDouble.doubleValue ();
// Ditto for numYears:
String numYearsString = numYearsField.getText ();
numYearsString = numYearsString.trim ();
Double numYearsDouble = new Double (numYearsString);
numYears = numYearsDouble.doubleValue ();
// Let's illustrate a shortcut that may be a little hard to understand:
rate = new Double (rateField.getText().trim()).doubleValue();
// Calculate the simple interest:
simpleInterest = (principal * rate * numYears) / 100;
amount = principal + simpleInterest;
// Redraw
repaint();
}
public void paint (Graphics g)
{
// Display the simple interest and amount:
g.drawString ("The simple interest and amount after " + numYears + " years", 60,100);
g.drawString (" Simple Interest: " + simpleInterest, 60,120);
g.drawString (" Total amount: " + amount, 60,140);
}
}
Note:
- The applet takes as input three numbers, computes two numbers
and prints these two numbers (interest and amount) out.
- We use three textfields to input the three numbers (principal,
rate and the number of years).
- We have declared five top-level variables: simpleInterest,
amount, principal, numYears, rate.
- These are declared to be of type double.
- double is used for floating point numbers.
- double is an example of a primitive or
basic type.
- As in previous applets, let's not worry about the GUI for now.
- Now, there are several steps in extracting a number from a
string, as shown in actionPerformed:
- The keyboard, through typing, creates strings.
These need to be converted to numbers.
- Once a string like 123.45 is created, we need
convert that to Java's internal representation of such
"floating point" or "real-valued" numbers.
- The steps involved are:
// Make sure whitespace on either side of the string is removed.
// This is done by callling the trim() method as below.
principalString = principalString.trim ();
// Next, create a Double object using the string.
Double principalDouble = new Double (principalString);
// The Double object has a method, doubleValue() which
// returns the actual double value.
principal = principalDouble.doubleValue ();
// The double value gets stored in the double variable,
// which in this case is "principal"
- The steps involved can be shortened into a single (somewhat
incomprehensible) line, as in:
rate = new Double (rateField.getText().trim()).doubleValue();
- For now, it's not important to understand the details, but
to know how to use this approach.
- Next, observe how calculations are done with variables,
with results assigned to variables:
// Calculate the simple interest:
simpleInterest = (principal * rate * numYears) / 100;
amount = principal + simpleInterest;
Integers
Let's modify the above example so that the number of years
is an integer:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class InterestCalcApplet2 extends Applet implements ActionListener {
// Three text fields:
TextField principalField, rateField, numYearsField;
// double variables we will need:
double simpleInterest = 0;
double amount = 0;
double principal = 0;
double rate = 0;
// int variable:
int numYears = 0;
public void init()
{
// Create the textfields, labels and button.
principalField = new TextField (6);
rateField = new TextField (6);
numYearsField = new TextField (6);
Label principalLabel = new Label ("Principal ");
Label rateLabel = new Label ("Rate (%) ");
Label numYearsLabel = new Label ("Time (in years) ");
Button calcButton = new Button ("Calculate");
// Lay out the components.
add (principalLabel);
add (principalField);
add (rateLabel);
add (rateField);
add (numYearsLabel);
add (numYearsField);
add (calcButton);
// Add the applet as listener to the calc button so that
// actionPerformed (below) is called when the button is clicked.
calcButton.addActionListener (this);
}
public void actionPerformed (ActionEvent e)
{
// Principal and rate, as before:
principal = new Double (principalField.getText().trim()).doubleValue();
rate = new Double (rateField.getText().trim()).doubleValue();
// Note the equivalent use of Integer and intValue():
numYears = new Integer (numYearsField.getText().trim()).intValue();
// Calculation stays the same:
simpleInterest = (principal * rate * numYears) / 100;
amount = principal + simpleInterest;
// Redraw
repaint();
}
public void paint (Graphics g)
{
// Display the simple interest and amount:
g.drawString ("The simple interest and amount after " + numYears + " years", 60,100);
g.drawString (" Simple Interest: " + simpleInterest, 60,120);
g.drawString (" Total amount: " + amount, 60,140);
}
}
Note:
- Converting an integer in a string representation to an actual
Java int is similar to the double conversion we
say earlier.
- Both int and double variables can be used
in calculations together.
- Link to applet
- What happens if you enter a real number into an integer field?
Special math functions
The Java library provides a number of functions for use
in mathematical calculations:
- For example, here's how we might compute the square root:
double x = 16.0;
double sqrtOfX = Math.sqrt (x);
In-Class Exercise:
Look up Math in the API documentation and write down
the list of available functions.
In-Class Exercise:
Write an applet that takes two numbers x and y as input and
that computes and writes out xy.
Casting
Consider this variation of interest calculation:
- Suppose we want the principal and interest to be integers.
- The percent computation can result in a real number
(e.g., 5% of 55).
- Suppose we want the resulting output to be integers.
=> we need a way of converting double variables
to int's.
- See the applet
This example shows how:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class IntegerPercentApplet extends Applet implements ActionListener {
TextField principalField, rateField;
// Variables - all integers:
int simpleInterest = 0;
int principal = 0;
int rate = 0;
int amount = 0;
public void init()
{
// ... not shown ...
}
public void actionPerformed (ActionEvent e)
{
// Retrieve from text fields and convert to int's:
principal = new Integer (principalField.getText().trim()).intValue();
rate = new Integer (rateField.getText().trim()).intValue();
// The computation results in double:
double tempInterest = (principal * rate) / 100.0;
// Cast the double to an int:
simpleInterest = (int) tempInterest;
// This is purely an integer calculation:
amount = principal + simpleInterest;
// Redraw
repaint();
}
public void paint (Graphics g)
{
// ... same as before ...
}
}
Note:
- You can assign an int to a double as follows:
int i = 5;
double x = 1.23;
x = i; // Now x has the value 5.0
- However, you cannot assign a double to an int
directly, as in:
int i = 5;
double x = 1.23;
i = x; // Will not compile.
- To make such an assignment, you need an explicit cast:
int i = 5;
double x = 1.23;
i = (int) x; // Works. Now i has the value 1.
- So, what is casting?
- An int can be stored in a double variable
with no loss of information.
- The reverse is not true (e.g, we "lost" the 0.23 part of 1.23
above).
- The compiler will not allow such direct loss of information
without an explicit cast.
- To cast, place the desired type in parenthesis as shown:
i = (int) x;
- In an explicit cast, you are telling the compiler "Hey, I
want this to happen. I'm OK with the loss of information".
In-Class Exercise:
Write an applet that takes two integers x and y as input and
that computes and writes out xy.
In-Class Exercise:
Write an applet that uses the ++ (increment)
operator for integers.