Java Mathbook
Java Mathbook
by
John Sweeney
Rochester Institute of Technology
Java for Mathematicians/Page 2
Topic: Goal
Topic: Preparation
Topic: IDE
/**
* The FamousMathQuotes class
* This computer program prints a famous quote of
Carl Friedrich Gauss.
*/
class FamousMathQuotes {
Topic: Comments
Java for Mathematicians/Page 9
/**
* Program goal, algorithms, and
* data structures are described here.
*/
class FamousMathQuotes {
Topic: Class
class FamousMathQuotes {
...
}
attributes.
Within the class you will notice "public static
void main(String[] args)" which describes the method
named "main." In a world of objects the modifier
"public" means other objects can see and use your
method named "main." Classes are used to make objects.
/**
* The FamousMathQuotes class
* simply prints a famous quote of Carl Friedrich
Gauss to standard output.
*/
class FamousMathQuotesV2 {
/**
* Method go prints
* a famous quote of Carl Friedrich Gauss to
standard output.
*/
private void go()
{
System.out.println("Carl Friedrich Gauss
described mathematics as the Queen of the Sciences.");
// Display the string.
}
/**
* The main method is automatically executed.
*/
public static void main(String[] args) {
FamousMathQuotesV2 entity = new
FamousMathQuotesV2();
entity.go();
}
}
Java for Mathematicians/Page 14
/**
* Print the sum of 6's proper positive divisors.
*/
public class SumPositiveDivisors {
/**
* This method prints the sum of 6's proper
positive divisors.
*/
private void go()
{
int divisor1 = 1;
int divisor2 = 2;
int divisor3 = 3;
int sum = divisor1 + divisor2 + divisor3;
System.out.println(sum); // Display the
answer.
}
Java for Mathematicians/Page 17
/**
* The main method is automatically executed.
* Create an object of class SumTwoIntegers
* then call its method named go.
*/
public static void main(String[] args) {
SumPositiveDivisors entity = new
SumPositiveDivisors();
entity.go();
}
1 /**
2 * Print the sum of 6's proper positive divisors.
3 */
4 public class SumPositiveDivisorsV5 {
5
6 /**
7 * This method prints the sum of 6's proper
positive divisors.
8 */
9 private void go()
Java for Mathematicians/Page 24
10 {
11 int divisor1 = 1;
12 int divisor2 = 2;
13 int divisor3 = 3;
14 int sum = divisor1 + divisor1 + divisor3;
15 System.out.println(sum); // Display the
answer.
16 }
17
18 /**
19 * The main method is automatically executed.
20 * Create an object of class SumTwoIntegers
21 * then call its method named go.
22 */
23 public static void main(String[] args) {
24 SumPositiveDivisorsV5 entity = new
SumPositiveDivisorsV5();
25 entity.go();
26 }
27
28 }
Topic: approximations
/**
* Print three historical approximations of pi.
*/
public class ApproximatePi {
/**
* This method prints the sum of 6's proper positive
divisors.
*/
private void calc()
{
System.out.println("Math.pi: " + Math.PI);
/**
* The main method is automatically executed.
* Create an object of class ApproximatePi
* then call its method named calc.
*/
public static void main(String[] args) {
ApproximatePi object = new ApproximatePi();
object.calc();
}
ÏÏÏMath.pi: 3.141592653589793
ÏÏÏAhmes 256/81: 3.1604938271604937
ÏÏÏBabylonian 25/8: 3.125
ÏÏÏArchimedes 22/7: 3.142857142857143
/**
* Print three historical approximations of pi.
*/
public class ApproximatePi {
/**
* This method prints the sum of 6's proper positive
divisors.
*/
private void calc()
{
System.out.println("Math.pi: " + Math.PI);
/**
* The main method is automatically executed.
* Create an object of class ApproximatePi
* then call its method named calc.
*/
public static void main(String[] args) {
ApproximatePi object = new ApproximatePi();
object.calc();
}
Math.pi: 3.141592653589793
Ahmes 256/81: 3.0
Babylonian 25/8: 3.125
Archimedes 22/7: 3.142857142857143
/**
* Print an example overflow condition for an int.
*/
public class OverflowError {
/**
* This method prints the sum of 6's proper positive
divisors.
*/
Java for Mathematicians/Page 30
/**
* The main method is automatically executed.
* Create an object of class OverflowError
* then call its method named calc.
*/
public static void main(String[] args) {
OverflowError object = new OverflowError();
object.calc();
}
Topic: Activity
Topic: Classes
/**
* This class represents a square in two dimensions.
*/
public class Square {
/**
* This class represents a square in two dimensions.
*/
public class Square {
double side;
/**
* This class represents a square in two dimension.
*/
public class Square {
/**
Java for Mathematicians/Page 35
/**
* This accessor method returns the length of the
square's side.
*
* @return the length of the square's edge
*/
public double getSide() {
return side;
}
/**
* This mutator method sets the length of the
square's side.
*
* @param _side the new length for the square's edge
*/
public void setSide(double _side) {
side = _side;
area = side * side;
}
/**
* This accessor method returns the area of the
square.
*
Java for Mathematicians/Page 36
//**
Java for Mathematicians/Page 37
/**
* This accessor method returns the length of the
square's side.
*
* @return double the area of the square
*/
public double getSide() {
return side;
}
/**
* This mutator method sets the length of the
square's side.
*
* @param side the new length for the square's edge
*/
public void setSide(double side) {
this.side = side;
}
/**
* This class represents a square in two dimension.
*/
public class Square {
/**
* This default constructor makes objects of class
Square.
*/
public Square() {
side = 0.0;
}
/**
* This accessor method returns the length of the
square's side.
*
* @return the length of the square's edge
*/
Java for Mathematicians/Page 39
/**
* This mutator method sets the length of the
square's side.
*
* @param _side the new length for the square's edge
*/
public void setSide(double _side) {
side = _side;
area = side * side;
}
/**
* This class represents a square in two dimension.
*/
public class Square {
/**
* This default constructor makes objects of class
Square.
*/
public Square() {
side = 0.0;
area = 0.0;
}
/**
* This accessor method returns the length of the
square's side.
*
* @return the length of the square's edge
*/
public double getSide() {
return side;
}
/**
* This mutator method sets the length of the
square's side.
*
* @param _side the new length for the square's edge
*/
public void setSide(double _side) {
side = _side;
area = side * side;
}
/**
* This accessor method returns the area of the
Java for Mathematicians/Page 41
square.
*
* @return the area of the square
*/
public double getArea() {
return area;
}
/**
* This default constructor makes objects of class
Square.
*/
public Square() {
side = 0.0;
}
Java for Mathematicians/Page 45
/**
* This fully parametrized default constructor makes
objects of class Square.
*/
public SquareV2(double _side) {
side = _side;
}
//**
* This class represents a square in two dimensions.
*/
public class Square {
/**
* This default constructor makes objects of class
Square.
*/
public Square() {
Java for Mathematicians/Page 46
side = 0.0;
}
/**
* This fully parametrized default constructor makes
objects of class Square.
*/
public Square(double _side) {
side = _side;
}
/**
* This accessor method returns the length of the
square's side.
*/
public double getSide() {
return side;
}
/**
* This mutator method sets the length of the
square's side.
*/
public void setSide(double _side) {
side = _side;
}
/**
* This accessor method returns the area of the
square.
*/
public double getArea() {
// return side * side; or side raised to the
power of 2
return Math.pow(side,2);
}
/**
* This accessor method returns the area of the
square.
*/
public double getPerimeter() {
final int NUMBER_SIDES = 4;
return side * NUMBER_SIDES;
Java for Mathematicians/Page 48
/**
* This class represents a square in two dimensions.
*/
public class Square {
/**
* This default constructor makes objects of class
Square.
*/
public Square() {
side = 0.0;
}
/**
* This fully parametrized default constructor makes
objects of class Square.
Java for Mathematicians/Page 49
*/
public Square(double _side) {
side = _side;
}
/**
* This accessor method returns the length of the
square's side.
*/
public double getSide() {
return side;
}
/**
* This mutator method sets the length of the
square's side.
*/
public void setSide(double _side) {
side = _side;
}
/**
* This accessor method returns the area of the
square.
*/
public double getArea() {
// return side * side;
return Math.pow(side,2);
}
/**
* This accessor method returns the area of the
square.
*/
public double getPerimeter() {
final int NUMBER_SIDES = 4;
return side * NUMBER_SIDES;
Java for Mathematicians/Page 50
Topic: Exercise
/**
* This class tests class Square which represents a
square in two dimension.
*/
public class TestSquare {
/**
* This method creates an object of class Square
* and displays information concerning that square.
*/
private void go()
{
System.out.println("Create an object of class
Square.”);
}
Java for Mathematicians/Page 51
/**
* The main method is automatically executed.
* Create an object of class TestSquare
* then call its method named go.
*/
public static void main(String[] args) {
TestSquare entity = new TestSquare();
entity.go();
}
/**
* This class tests class Square which represents a
square in two dimension.
*/
public class TestSquare {
/**
* This method creates an object of class Square
* and displays information concerning that square.
*/
private void go()
{
Square sq = new Square();
System.out.println("Default square side: " +
sq.getSide() +
" area: " + sq.getArea() +
" perimeter: " + sq.getPerimeter()); //
Java for Mathematicians/Page 52
/**
* The main method is automatically executed.
* Create an object of class TestSquare
* then call its method named go.
*/
public static void main(String[] args) {
TestSquare entity = new TestSquare();
entity.go();
}
/**
* This fully parametrized constructor makes objects
of class Square.
Java for Mathematicians/Page 53
*/
public SquareV2(double _side) {
side = _side;
}
static rint(double a)
Java for Mathematicians/Page 55
Topic: Inheritance
import java.awt.Color;
/**
* This class represents a square in two dimension.
*/
public class ColorSquare extends Square {
/**
* This default constructor makes objects of class
Square.
*/
public ColorSquare() {
color = Color.RED;
}
Java for Mathematicians/Page 56
/**
* This accessor method returns the length of the
square's side.
*/
public Color getColor() {
return color;
}
/**
* This mutator method sets the length of the
square's side.
*/
public void setColor(Color _color) {
color = _color;
}
import java.awt.Color;
/**
* This class represents a triangle in two dimension.
*/
public class TestColorSquare {
/**
* This method creates an object of class Square
* and displays information concerning that square.
*/
private void go()
{
ColorSquare sq = new ColorSquare();
System.out.println("Default square side: " +
sq.getSide() +
Java for Mathematicians/Page 58
/**
* The main method is automatically executed.
* Create an object of class SumTwoIntegers
* then call its method named go.
*/
public static void main(String[] args) {
TestColorSquare entity = new TestColorSquare();
entity.go();
}
Topic: ArrayList
import java.util.ArrayList;
/**
* This class sums the area of several objects of class
Square.
*/
public class SumSquares {
/**
* This method creates several objects of class
Square
* and displays information concerning those
squares.
*/
private void go()
{
ArrayList<Square> squares = new
ArrayList<Square>();
Java for Mathematicians/Page 62
/**
* The main method is automatically executed.
* Create an object of class SumSquares
* then call its method named go.
*/
public static void main(String[] args) {
SumSquares entity = new SumSquares();
entity.go();
}
import java.awt.Color;
import java.util.ArrayList;
/**
* This class sums the area of several objects of class
Square.
*/
public class SumSquaresV2 {
/**
* This method creates several objects of class
Square
* and displays information concerning those squares.
*/
private void go()
{
ArrayList<Square> squares = new
ArrayList<Square>();
Square sq1 = new Square(1.2);
squares.add(sq1);
Square sq2 = new Square(0.5);
squares.add(sq2);
ColorSquare sq3 = new ColorSquare();
sq3.setSide(5.2);
sq3.setColor(Color.BLUE);
squares.add(sq3);
double sum = 0.0;
for (Square sq: squares)
{
sum = sum + sq.getArea();
Java for Mathematicians/Page 64
}
System.out.println("Total area: " + sum);
}
/**
* The main method is automatically executed.
* Create an object of class SumSquares
* then call its method named go.
*/
public static void main(String[] args) {
SumSquaresV2 entity = new SumSquaresV2();
entity.go();
}
Topic: IF statement
double largest = 0;
double largest = 0;
for (Square sq: squares)
{
if (sq.getArea() > largest)
{
largest = sq.getArea();
}
}
System.out.println("Area of largest square: " +
largest);
{
if (sq.getArea() < smallest)
{
smallest = sq.getArea();
}
}
System.out.println("Area of smallest square: " +
smallest);
Topic: Exercise
opposite vertexes).
Two of the most complicated of these figures are; the penton, with
proportions 1:√φ is related to the section of the golden pyramid,
the bipenton's longer side is equal to the shorter multiplied by two thirds of
the square root of three, longer side of the biauron is √5 - 1 or 2τ times the
shorter.
The quadriagon is related to the diagon in the
sense that its longer side is produced by projecting
the diagonal of a quarter of a square. The trion has
the height of an equilateral triangle and the width of
the side. The hemidiagon (1:½√5) longer side is half
the one of the root-5 rectangle and is produced by
projecting the diagonal of half a square until it is
perpendicular with the origin.
Besides the square and the double square, the
only other static rectangle included in the list is
the hemiolion, which is produced by projecting 90° or
180° half the side of a square.” Source: Wikipedia
Dynamic Rectangle.
http://en.wikipedia.org/wiki/Figurate_number gives an
equation for calculating the size of each triangular
number of number n as n(n+1)/2.
/**
* Triangular numbers can be represented by a group of
Java for Mathematicians/Page 70
dots
* organized in an equilateral triangle.
* The first few triangular numbers are of size 0, 1,
3,
* 6, and 10. Those are the sizes of
* triangles with edge length of 0, 1, 2, 3, and 4.
* The edge lengths are the IDs for those
* triangular numbers. Only one instance should be
made for each ID.
* Class TriangleNumber represents a single triangular
number.
*/
/**
* This default constructor makes instance zero of
class TriangleNumber.
*/
TriangleNumber()
{
tn = 0;
}
/**
* This fully parametrized constructor makes
instance n of class TriangleNumber.
*
* @param n the ID for an instance of
TriangleNumber of size n
Java for Mathematicians/Page 71
*/
public TriangleNumber(int n)
{
tn = n;
}
/**
* Returns the ID for this instance of
TriangleNumber.
*
* @return returns the ID of this instance of
TriangleNumber
*/
public int getID()
{
return tn;
}
/**
* This pseudo accessor calculates the size of this
instance of
* class TriangleNumber according to the equation
found in
* http://en.wikipedia.org/wiki/Figurate_number.
*
* @return the value or size of the triangle
*/
public int getValue()
{
return (tn * (tn + 1)) / 2;
}
/**
Java for Mathematicians/Page 72
/**
* Overrides toString method to display tn: value
*
* @return returns String tn: size
*/
public String toString()
{
return "t" + getID() + ": " + getValue();
}
class TestOneTriangleNumber
{
class TestOneTriangleNumber
{
import javax.swing.JOptionPane;
Java for Mathematicians/Page 74
import javax.swing.JOptionPane;
class TestOneTriangleNumberV2
{
}
Java for Mathematicians/Page 75
class ListTriangleNumbers
{
/*
OEIS: On-Line Encyclopedia of Integer Sequences
The sequence of triangular numbers (sequence
A000217 in OEIS),
starting at the 0th triangular number, is:
Java for Mathematicians/Page 77
/**
* Each instance of this class represents a square
number.
* They are 0, 4, 9, 16, etc.
*/
public class SquareNumber
{
/**
* This default constructor creates an instance of
SquareNumber with ID of 0.
*/
public SquareNumber()
{
sqN = 0;
}
/**
* This fully parametrized constructor creates an
instance of
* SquareNumber with ID of n.
*/
public SquareNumber(int n)
{
sqN = n;
}
Java for Mathematicians/Page 79
/**
* This accessor returns the instance's ID.
*
* @return the square number's ID
*/
public int getID()
{
return sqN;
}
/**
* This virtual accessor returns the size of the
square number.
*
* @return the size of the square number
*/
public int getValue()
{
return sqN * sqN;
}
/**
* This virtual accessor returns the additional
amount needed
* to increase to the next square number. This is
the edge across
* the top and on the right side of the current
square. Thus
* the gnomon is 2*n + 1.
*
* @return gnomon for this square
*/
Java for Mathematicians/Page 80
class ListSquareNumbers
{
/*
OEIS: On-Line Encyclopedia of Integer Sequences
The squares (sequence A000290 in OEIS) smaller
than 602 are:
0**2 = 0
1**2 = 1
2**2 = 4
3**2 = 9
4**2 = 16
5**2 = 25
6**2 = 36
7**2 = 49
8**2 = 64
9**2 = 81`
*/
public static void main(String[] args)
{
Java for Mathematicians/Page 81
Topic: Interfaces
// Polygonal Numbers
/**
* Triangular numbers can be represented by a group of
dots
* organized in an equilateral triangle.
* The first few triangular numbers are of size 0, 1,
3,
Java for Mathematicians/Page 83
/**
* This default constructor makes instance zero of
class TriangleNumber.
*/
TriangleNumber()
{
tn = 0;
}
/**
* This fully parametrized constructor makes
instance n of class TriangleNumber.
*
* @param n the ID for an instance of
TriangleNumber of size n
*/
public TriangleNumber(int n)
{
tn = n;
}
Java for Mathematicians/Page 84
/**
* Returns the ID for this instance of
TriangleNumber.
*
* @return returns the ID of this instance of
TriangleNumber
*/
public int getID()
{
return tn;
}
/**
* This pseudo accessor calculates the size of this
instance of
* class TriangleNumber according to the equation
found in
* http://en.wikipedia.org/wiki/Figurate_number.
*
* @return the value or size of the triangle
*/
public int getValue()
{
return (tn * (tn + 1)) / 2;
}
/**
* The gnomon is how much must be added to produce
the
* next triangular number. This is a pseudo-
accessor.
* @return gnomon
Java for Mathematicians/Page 85
*/
public int getGnomon()
{
return tn + 1;
}
/**
* Overrides toString method to display tn: value
*
* @return returns String tn: size
*/
public String toString()
{
return "t" + getID() + ": " + getValue();
}
/**
* Each instance of this class represents a square
number.
* They are 0, 4, 9, 16, etc.
*/
public class SquareNumber implements PolygonalNumber
{
/**
* This default constructor creates an instance of
Java for Mathematicians/Page 86
SquareNumber with ID of 0.
*/
public SquareNumber()
{
sqN = 0;
}
/**
* This fully parametrized constructor creates an
instance of
* SquareNumber with ID of n.
*/
public SquareNumber(int n)
{
sqN = n;
}
/**
* This accessor returns the instance's ID.
*
* @return the square number's ID
*/
public int getID()
{
return sqN;
}
/**
* This virtual accessor returns the size of the
square number.
*
* @return the size of the square number
*/
Java for Mathematicians/Page 87
/**
* This virtual accessor returns the additional
amount needed
* to increase to the next square number. This is
the edge across
* the top and on the right side of the current
square. Thus
* the gnomon is 2*n + 1.
*
* @return gnomon for this square
*/
public int getGnomon()
{
return (2 * sqN) + 1;
}
int n = 0;
TriangleNumber tri = new TriangleNumber(n);
int gnomon = tri.getGnomon ();
Java for Mathematicians/Page 89
import java.util.ArrayList;
class FindNumberTypes
{
Java for Mathematicians/Page 90
/*
OEIS: On-Line Encyclopedia of Integer Sequences
The squares (sequence A000290 in OEIS) smaller than
602 are:
0**2 = 0
1**2 = 1
2**2 = 4
3**2 = 9
4**2 = 16
5**2 = 25
6**2 = 36
7**2 = 49
8**2 = 64
9**2 = 81`
*/
/*
OEIS: On-Line Encyclopedia of Integer Sequences
The sequence of triangular numbers (sequence
A000217 in OEIS),
starting at the 0th triangular number, is:
0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91,
105, 120
` */
{
final int TARGET = 73;
ArrayList<PolygonalNumber> polygonalNumbers =
new ArrayList<>();
gnomon = tri.getGnomon();
}
Topic: Refactoring
Java for Mathematicians/Page 93
int id = 0;
int gnomon = 0;
int value = 0;
while (( gnomon < TARGET ) ||
( value < TARGET))
{
PolygonalNumber polyNum =
pnFactory.createPolygonalNumber(pn, id);
polygonalNumbers.add(polyNum);
id++;
value = polyNum.getValue();
gnomon = polyNum.getGnomon();
// System.out.println("Add to array pn: " +
pn + " id: " + id + " value: " + value + "
Java for Mathematicians/Page 95
ArrayList<PolygonalNumber> polygonalNumbers =
new ArrayList<>();
/**
* Creates instances of the concrete classes that
* implement the PolygonalNumber interface.
*/
public class PolygonalNumberFactory
{
/**
* This method returns an instance of a concrete
* class that implements the PolygonalNumber interface.
Java for Mathematicians/Page 97
*
* @return instance of concrete class implement
PolygonalNumber interface
*/
public PolygonalNumber createPolygonalNumber(String
concreteClass, int id)
{
PolygonalNumber pn = null;
switch(concreteClass)
{
case "TRIANGLE":
pn = new TriangleNumber(id);
break;
case "SQUARE":
pn = new SquareNumber(id);
break;
}
return pn;
}
}
switch(concreteClass)
{
case "TRIANGLE":
Java for Mathematicians/Page 98
pn = new TriangleNumber(id);
break;
case "SQUARE":
pn = new SquareNumber(id);
break;
case "PENTAGONAL":
pn = new PentagonalNumber(id);
break;
case "HEXAGON":
pn = new HexagonNumber(id);
break;
case "HEPTAGONAL":
pn = new HeptagonalNumber(id);
break;
}
return pn;
/**
* Creates instances of the concrete classes that
* implement the PolygonalNumber interface.
*/
public class PolygonalNumberFactoryv2
{
Java for Mathematicians/Page 99
/**
* This method returns an instance of a concrete
* class that implements the PolygonalNumber
interface.
*
* @return instance of concrete class implement
PolygonalNumber interface
*/
ÏÏ§Ï ^
ÏϧÏ1 error
ÏϧÏ
Topic: Activity
Source: http://docs.oracle.com/javase/tutorial/2d/overview/coordinate.html
/**
Use only the one quadrant of the Cartesian grid
with positive x and y coordinates. The origin (0,0) is
at the top left corner. The x-coordinate increases
from left to right. The y-coordinate increases from
top to bottom. This description does not match the
diagram above.
*/
public abstract class CartesianShape
{
private double topLeftX;
// X coordinate of top left corner of bounding
rectangle
private double topLeftY;
// Y coordinate of top left corner of bounding
rectangle
Java for Mathematicians/Page 103
/**
default constructor. Shape is assumed to begin at
(0,0).
*/
public CartesianShape()
{
topLeftX = 0;
topLeftY = 0;
}
/**
full constructor.
*/
public CartesianShape(double x, double y)
{
topLeftX = x;
topLeftY = y;
}
/**
Return x coordinate of top left corner
of bounding rectangle.
*/
public double getTopLeftX()
{
return topLeftX;
}
/**
set x coordinate of top left corner of
bounding rectangle.
*/
public void setTopLeftX(int x)
Java for Mathematicians/Page 104
{
topLeftX = x;
}
/**
Return y coordinate of top left corner
of bounding rectangle.
*/
public double getTopLeftY()
{
return topLeftY;
}
/**
set y coordinate of top left corner of
bounding rectangle.
*/
public void setTopLeftY(double y)
{
topLeftY = y;
}
/**
Increment x and y coordinates of top left
corner
of bounding rectangle.
*/
public void move(double x, double y)
{
topLeftX += x;
topLeftY += y;
}
Java for Mathematicians/Page 105
/**
Change x and y coordinates of top left corner
of bounding rectangle.
*/
public void moveTo(double x, double y)
{
topLeftX = x;
topLeftY = y;
}
/**
Return area of shape. Zero if not closed
loop..
*/
public abstract double getArea();
/**
Extends CartesianShape to define a Cartesian grid
based rectangle.
The rectangle is always oriented along the x and y
axes.
*/
public class CartesianRectangle extends CartesianShape
{
/**
Default constructor
*/
public CartesianRectangle()
{
length = 0;
width = 0;
}
/**
Fully parametrized constructor
*/
public CartesianRectangle(double x, double y,
double len, double wide)
Java for Mathematicians/Page 107
{
super(x,y);
if (len >= 0 && wide >= 0)
{
length = len;
width = wide;
}
}
/**
Accessor for attribute length
*/
public double getLength()
{
return length;
}
/**
Mutator for attribute length
*/
public void setLength(double len)
{
if (len >= 0)
{
length = len;
}
}
/**
Accessor for attribute width
*/
public double getWidth()
{
Java for Mathematicians/Page 108
return width;
}
/**
Mutator for attribute width
*/
public void setWidth(double wide)
{
if (wide >= 0)
{
length = wide;
}
}
/**
Defines the abstract method of
CartesianShape.
GetArea acts likes an accessor, so
area is a pseudo-attribute.
*/
public double getArea()
{
return length * width;
}
}
Java for Mathematicians/Page 110
Source:
http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html
Java for Mathematicians/Page 111
}
}
CartesianRectangle@1cd8f55c
CartesianRectangle@67d479cf
rectangle 2 moved to (100,200).
CartesianRectangle@67d479cf
/**
Override default toString method inherited from
object named Object.
*/
public String toString()
{
return "rectangle at (" + getTopLeftX() + ","
+ getTopLeftY() + ") length: " + length + " width: "
+ width + " area: " + getArea();
}
Source: http://xkcd.com/994/
Topic: GUI
Topic: JFrame
/**
Use JFrame for a GUI program
*/
import javax.swing.JFrame;
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int width = 300;
int length = 300;
window.setBounds(30, 30, width, length);
window.setTitle("Draw Cartesian Objects");
window.setVisible(true);
}
The commands
int width = 300;
int length = 300;
window.setBounds(30, 30, width, length);
Java for Mathematicians/Page 117
int x = 10;
int y = 10;
int width = 200;
int height = 200;
// Draw outline of rectangle
Rectangle surround = new Rectangle(x, y,
width, height);
g2.draw(surround);
}
}
import java.awt.*;
import java.awt.Graphics;
import java.awt.Rectangle;
Java for Mathematicians/Page 121
import javax.swing.JComponent;
import javax.swing.JFrame;
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int width = 300;
int length = 300;
window.setBounds(30, 30, width, length);
window.add(new MyCanvas());
window.setVisible(true);
}
}
Java for Mathematicians/Page 122
g2.setColor(color);
Topic: Activity
Topic: array
int[] primes;
primes = { 1, 2, 3, 5, 7, 9, 11, 13, 17, 19, 23,
25,
29, 31, 33, 35, 37, 41, 43, 47, 49, 53, 59, 61,
65,
67, 69, 71, 73, 77, 79, 83, 89, 91, 97, 101,
Java for Mathematicians/Page 128
103, 107,
109, 113, 125, 127, 129, 131, 133, 137, 139,
141, 143,
145, 149, 151, 155, 157, 161, 163, 167, 169,
173, 179, 181 };
/**
Java for Mathematicians/Page 129
/**
default constructor
*/
public Primes()
{
/*
This method works with the prime numbers.
*/
private void go()
{
Java for Mathematicians/Page 130
/**
main method
obj is a common abbreviation of "object".
*/
public static void main(String[] args)
{
Primes obj = new Primes();
obj.go();
}
Program Results
/**
This class works with the prime numbers from 1
through 181.
*/
public class PrimeNumbers
{
// An array of int primitive values, not object
instances of classes
// List of prime numbers. Source:
http://oeis.org/A090332
private int[] primes = { 1, 2, 3, 5, 7, 9, 11, 13,
17, 19, 23, 25,
29, 31, 33, 35, 37, 41, 43, 47, 49, 53, 59, 61,
65,
67, 69, 71, 73, 77, 79, 83, 89, 91, 97, 101,
103, 107,
109, 113, 125, 127, 129, 131, 133, 137, 139,
141, 143,
145, 149, 151, 155, 157, 161, 163, 167, 169,
Java for Mathematicians/Page 133
/**
default constructor
*/
public PrimeNumbers()
{
/**
Test if an integer is a prime.
*/
public boolean isPrime(int n)
{
boolean answer = false;
for (int prime : primes) // foreach prime
in primes
if (n == prime) // test prime
{
answer = true;
break; // interrupt loop
}
return answer;
}
/**
* Return prime from array.
*/
public int getPrime(int index)
{
return primes[index];
}
Java for Mathematicians/Page 134
/**
* Return largest prime from array, which is the
last entry.
*/
public int getMaxPrime()
{
return primes[primes.length-1];
}
/**
* Return prime from array.
*/
public int getMaxCntPrimes()
{
return primes.length;
}
Topic: Scope
/**
* Return prime from array.
*/
public int getMaxCntPrimes()
{
return primes.length;
}
/**
* Return prime from array.
*/
public int getPrime(int index)
{
Java for Mathematicians/Page 136
return primes[index];
}
/**
* Return largest prime from array, which is the
last entry.
*/
public int getMaxPrime()
{
return primes[primes.length - 1];
}
/**
Test if an integer is a prime.
*/
public boolean isPrime(int n)
{
boolean answer = false;
for (int prime : primes) // for each prime
in primes
if (n == prime) // test prime
{
return true;
}
return answer;
}
/**
Test if an integer is a prime.
*/
public boolean isPrime(int n)
{
boolean answer = false;
for (int prime : primes) // foreach prime
in primes
if (n == prime) // test prime
{
answer = true;
break; // interrupt loop
}
return answer;
}
/**
* Return +1 for positive integers
* Return -1 for negative integers
* Print "zero" for integer zero.
*/
public class PositiveInteger
{
return 1;
}
else if (i < 0) {
return -1;
}
else {
System.out.println("zero");
}
}
/**
* Return +1 for positive integers
* Return -1 for negative integers
* Print 0 for integer zero.
*/
public class PositiveInteger
{
Java for Mathematicians/Page 140
/**
* Return +1 for positive integers
* Return -1 for negative integers
* Print 0 for integer zero.
*/
public class PositiveInteger
{
Java for Mathematicians/Page 141
Topic: Big O
/**
Test if an integer is a prime.
*/
public boolean isPrime(int n)
{
Java for Mathematicians/Page 142
import java.util.Scanner;
/**
* Test class Primes
*/
public class TestPrimeNumbers
{
Primes p;
/**
* constructor
*/
public TestPrimeNumbers()
{
p = new PrimeNumbers();
}
/**
This method lists all the prime numbers in the
list.
*/
private void list()
{
System.out.println("prime numbers in list:");
int maxIndex = p.getMaxCntPrimes();
for (int i = 0; i < maxIndex; i++)
{
System.out.println(p.getPrime(i)); // print
prime
}
}
Java for Mathematicians/Page 144
/**
This method prints the largest prime numbers in
the list.
*/
private void maxPrime()
{
System.out.println("The largest prime in this
list: " + p.getMaxPrime());
}
/**
This method prints the count of prime numbers in
the list.
*/
private void cntPrime()
{
System.out.println("The count of prime numbers
in this list: " + p.getMaxCntPrimes());
}
/**
This method checks whether or not an integer is
in the list of prime numbers.
*/
private void chkPrime()
{
// Check 4 as a prime number
System.out.print("prime candidate: ");
int candidate = 4;
System.out.print(candidate + " is ");
if (p.isPrime(candidate) == false)
{
Java for Mathematicians/Page 145
System.out.print("not ");
}
System.out.println("a prime number.");
// Check 5 as a prime number
System.out.print("prime candidate: ");
candidate = 5;
System.out.print(candidate + " is ");
if (p.isPrime(candidate) == false)
{
System.out.print("not ");
}
System.out.println("a prime number.");
}
/**
This method works with the prime numbers.
*/
private void go()
{
Scanner input = new Scanner(System.in);
final int EXIT = 0;
final int LIST = 1;
final int MAX = 2;
final int CNT = 3;
final int CHK = 4;
int choice = -1;
System.out.print("Testing class Primes \nSelect
1-List 2-Max 3-Count 4-prime 0-stop: ");
choice = input.nextInt();
while (choice > 0)
{
switch(choice) {
case EXIT:
Java for Mathematicians/Page 146
System.exit(0);
break;
case LIST:
list();
break;
case MAX:
maxPrime();
break;
case CNT:
cntPrime();
break;
case CHK:
chkPrime();
break;
default:
System.out.println("Enter 0, 1, 2, or
3.");
break;
}
System.out.print("Testing class Primes
\nSelect 1-List 2-Max 3-Count 4-Prime 0-stop: ");
choice = input.nextInt();
}
}
/**
main method
obj is a common abbreviation of "object".
*/
public static void main(String[] args)
{
TestPrimes obj = new TestPrimes();
obj.go();
Java for Mathematicians/Page 147
Topic: Scanner
Topic: Scope
/**
This method works with the prime numbers.
*/
Java for Mathematicians/Page 149
switch(choice) {
Java for Mathematicians/Page 151
case EXIT:
System.exit(0);
break;
case LIST:
list();
break;
case MAX:
// maxPrime();
System.out.println("The largest prime in
this list: " + p.getMaxPrime());
break;
case CNT:
cntPrime();
break;
case CHK:
chkPrime();
break;
default:
System.out.println("Enter 0, 1, 2, or
3.");
break;
}
commands.
/**
This method lists all the prime numbers in the
list.
*/
private void list()
{
System.out.println("prime numbers in list:");
int maxIndex = p.getMaxCntPrimes();
for (int i = 0; i < maxIndex; i++)
{
System.out.println(p.getPrime(i)); // print
prime
}
}
/**
Java for Mathematicians/Page 153
/**
This method lists all the prime numbers in the
list.
*/
private void list()
{
System.out.println("prime numbers in list:");
int[] primes = p.getArrayPrimes();
for (int prime : primes)
{
System.out.println(prime); // print prime
}
}
/**
This method lists all the prime numbers in the
list.
This method contains an error.
*/
private void list()
{
System.out.println("prime numbers in list:");
int maxIndex = p.getMaxCntPrimes();
for (int i = 0; i < maxIndex; i++)
{
int prime = p.getPrime(i);
System.out.println(prime); // print prime
/* The following command changes the value of
the local variable named prime. It does
not change the value in the PrimeNumbers
object.
*/
prime = 0;
}
}
Java for Mathematicians/Page 155
/**
This method lists all the prime numbers in the
list.
*/
private void list()
{
System.out.println("prime numbers in list:");
int[] primes = p.getArrayPrimes();
for (int i = 0; i < primes.length; i++)
{
int prime = primes[i];
System.out.println(prime); // print prime
// Change the prime to zero.
primes[i] = 0;
}
Java for Mathematicians/Page 156
/**
This method checks whether or not an integer is
in the list of prime numbers.
*/
private void chkPrime()
{
System.out.print("prime candidate: ");
int candidate = input.nextInt();
System.out.print(candidate + " is ");
if (p.isPrime(candidate) == false)
{
System.out.print("not ");
}
Java for Mathematicians/Page 158
import java.util.Scanner;
/**
* Test class Primes
*/
public class TestPrimeNumbers
{
PrimeNumbers p;
Scanner input;
/**
Java for Mathematicians/Page 159
* constructor
*/
public TestPrimeNumbers()
{
p = new PrimeNumbers();
input = new Scanner(System.in);
}
Topic: Recursion
/**
* Use a binary search to find whether or not an
integer is a prime number.
*/
private boolean binarySearchPrimes(int low, int
high, int candidate)
{
int middle = low + ((high - low) / 2);
if (candidate == primes[middle])
{
Java for Mathematicians/Page 163
return true;
}
else
{
if (low >= high)
{
return false;
}
else
{
if (candidate < primes[middle])
{
return binarySearchPrimes(low, middle-
1, candidate);
}
else
{
return binarySearchPrimes(middle+1,
high, candidate);
}
}
}
}
/**
Java for Mathematicians/Page 164
return rtnValue;
}
/**
* Use a binary search to find whether or not an
integer is a prime number.
*/
private boolean binarySearchPrimes(int low, int
high, int candidate)
{
boolean rtnValue = true;
int middle = low + ((high - low) / 2);
if (candidate == primes[middle])
rtnValue = true;
else if (low >= high)
rtnValue = false;
else if (candidate < primes[middle])
rtnValue = binarySearchPrimes(low, middle-1,
candidate);
else
rtnValue = binarySearchPrimes(middle+1, high,
candidate);
return rtnValue;
}
if (comparison)
statement;
else
statement;
if (condition)
{
statement;
}
else
{
statement;
}
/**
* Use a binary search to find whether or not an
Java for Mathematicians/Page 168
boolean rtnValue =
binarySearchPrimes(offset, low, middle-1, candidate);
System.out.println(offset + rtnValue);
return rtnValue;
}
else
{
// Recursive call using higher half of list
boolean rtnValue =
binarySearchPrimes(offset, middle+1, high, candidate);
System.out.println(offset + rtnValue);
return rtnValue;
}
}
}
}
if (candidate == primes[middle])
{
System.out.println(offset + "return true");
return true;
}
Java for Mathematicians/Page 170
offset += "..";
if (candidate < primes[middle])
{
boolean rtnValue = binarySearchPrimes(offset,
low, middle-1, candidate);
System.out.println(offset + rtnValue);
return rtnValue;
}
Topic: UML
import java.awt.geom.*;
/**
* Class Triange uses three Points to describe its
triangle.
*/
// Attributes
Point2D.Double pointA, pointB, pointC;
// Constructors
/**
* default constructor
*/
public Triangle()
{
Java for Mathematicians/Page 174
/**
* fully parametrized constructor
*/
public Triangle(Point2D.Double a, Point2D.Double b,
Point2D.Double c)
{
pointA = a;
pointB = b;
pointC = c;
}
/**
* getPointA returns the Point object for attribute
pointA
*/
public Point2D.Double getPointA()
{
return pointA;
}
/**
* setPointA sets pointA to the Point provided in
the list of arguments */
public void setPointA(Point2D.Double point)
{
Java for Mathematicians/Page 175
pointA = point;
}
/**
* getPointB returns the Point object for attribute
pointB
*/
public Point2D.Double getPointB()
{
return pointB;
}
/**
* getPointB sets pointB to the Point provided in
the list of arguments */
public void setPointB(Point2D.Double point)
{
pointB = point;
}
/**
* getPointC returns the Point object for attribute
pointC
*/
public Point2D.Double getPointC()
{
return pointC;
}
/**
* getPointA sets pointA to the Point provided in
the list of arguments
*/
Java for Mathematicians/Page 176
/**
* get length of side A - B
*/
public double getSideAB()
{
// Point2D.Double extends Point2D which provides
the distance method
return pointA.distance(pointB);
}
/**
* get length of side A - B
*/
public double getSideBC()
{
return pointB.distance(pointC);
}
/**
* get length of side A - B
*/
public double getSideAC()
{
return pointA.distance(pointC);
}
/**
* get perimeter of triangle
Java for Mathematicians/Page 177
*/
public double getPerimeter()
{
return getSideAB() + getSideBC() + getSideAC();
}
/**
* calculate area of triangle
* In geometry, Heron's (or Hero's) formula, named
after Heron of Alexandria,
* states that the area T of a triangle whose sides
have lengths a, b, and c is
* area = sqrt( s(s-a)(s-b)(s-c) )
* where s is the semiperimeter of the triangle.
* Source: http://en.wikipedia.org/wiki/Hero
%27s_formula
*/
public double getArea()
{
double s = getPerimeter() / 2;
double a = getSideAB();
double b = getSideBC();
double c = getSideAC();
double area = Math.sqrt(s * (s-a) * (s-b) * (s-
c));
return area;
}
// Attributes
Point2D.Double pointA, pointB, pointC;
// Attributes
Point2D.Double pointA;
Point2D.Double pointB;
Point2D.Double pointC;
…
}
/**
* default constructor
*/
public Triangle()
{
pointA = new Point2D.Double(); // by default set
to (0,0)
pointB = new Point2D.Double();
pointC = new Point2D.Double();
}
/**
* default constructor
* This constructor contains a serious ERROR
*/
public Triangle()
{
Java for Mathematicians/Page 181
/**
* fully parametrized constructor
*/
public Triangle(Point2D.Double a, Point2D.Double b,
Point2D.Double c)
{
pointA = a;
pointB = b;
pointC = c;
}
/**
* fully parametrized constructor has an ERROR in
* its list of arguments
* Each argument requires its own type declaration.
*/
public Triangle(Point2D.Double a, b, c)
{
pointA = a;
pointB = b;
pointC = c;
Java for Mathematicians/Page 182
/**
* get length of side A - B
*/
public double getSideAB()
{
// Point2D.Double extends Point2D which provides
the distance method
return pointA.distance(pointB);
}
/**
* calculate area of triangle
* In geometry, Heron's (or Hero's) formula, named
after Heron of Alexandria,
* states that the area T of a triangle whose sides
have lengths a, b, and c is
* T = sqrt( s(s-a)(s-b)(s-c) )
* where s is the semiperimeter of the triangle.
* Source: http://en.wikipedia.org/wiki/Hero
%27s_formula
*/
Java for Mathematicians/Page 183
import java.util.Scanner;
import java.awt.geom.*;
/**
* Test calculator of triangle facts
*/
/**
* Default constructor
*/
public TestTriangle()
{
}
Java for Mathematicians/Page 184
/**
* Go method
*/
private void go()
{
System.out.println("Start test of Triangle
object.");
Point2D.Double pointA = new Point2D.Double(0,0);
Point2D.Double pointB = new Point2D.Double(0,1);
Point2D.Double pointC = new Point2D.Double(1,1);
Triangle tri = new Triangle(pointA, pointB,
pointC);
Point2D.Double a = tri.getPointA();
Point2D.Double b = tri.getPointB();
Point2D.Double c = tri.getPointC();
System.out.println("Point A: (" + a.getX() + ","
+ a.getY() + ")" );
System.out.println("Point B: (" + b.getX() + ","
+ b.getY() + ")" );
System.out.println("Point C: (" + c.getX() + ","
+ c.getY() + ")" );
System.out.println("side AB: " + tri.getSideAB()
);
System.out.println("side BC: " + tri.getSideBC()
);
System.out.println("side AC: " + tri.getSideAC()
);
System.out.println("perimeter: " +
tri.getPerimeter());
System.out.println("area: " + tri.getArea() );
}
Java for Mathematicians/Page 185
/**
* Main method
*/
public static void main(String[] args)
{
System.out.println("Start test run of
calculator.");
TestTriangle obj = new TestTriangle();
obj.go();
}
Topic: printf
import java.util.Scanner;
import java.awt.geom.*;
/**
* Test calculator of triangle facts
*/
Scanner scan;
/**
* Default constructor
*/
public TestTriangleV2()
{
// initialize scanner
scan = new Scanner(System.in);
// Create default triangle
Point2D.Double pointA = new Point2D.Double(0,0);
Point2D.Double pointB = new Point2D.Double(0,1);
Point2D.Double pointC = new Point2D.Double(1,1);
Triangle tri = new Triangle(pointA, pointB,
pointC);
}
/**
Java for Mathematicians/Page 189
/**
* makeTriangle sets up a new triangle.
*/
private void makeTriangle()
{
Point2D.Double a = makePoint();
Point2D.Double b = makePoint();
Point2D.Double c = makePoint();
tri = new Triangle(a,b,c);
}
/**
* listTriPoints displays the (x,y) coordinates of
all three vertices
*/
private void listTriPoints()
{
Java for Mathematicians/Page 190
Point2D.Double a = tri.getPointA();
Point2D.Double b = tri.getPointB();
Point2D.Double c = tri.getPointC();
System.out.println("Triangle");
System.out.printf("Vertex\tx\ty\n");
System.out.printf("%c\t%5.3f\t%5.3f\n", 'A',
a.getX(), a.getY());
System.out.printf("%c\t%5.3f\t%5.3f\n", 'B',
b.getX(), b.getY());
System.out.printf("%c\t%5.3f\t%5.3f\n", 'C',
c.getX(), c.getY());
}
/**
* Go method
*/
private void go()
{
boolean done = false;
System.out.println("Start test of Triangle
object.");
System.out.print("Enter 0-exit 1-setup 2-list 3-
perimeter 4-area: ");
int choice = scan.nextInt();
while (choice != 0)
{
switch(choice)
{
case 0:
System.out.println("bye");
System.exit(0);
case 1:
makeTriangle();
Java for Mathematicians/Page 191
break;
case 2:
listTriPoints();
break;
case 3:
System.out.printf("perimeter: %.3f\n",
tri.getPerimeter());
break;
case 4:
System.out.printf("area: %.3f\n",
tri.getArea());
break;
default:
System.out.println("Enter 0, 1, 2, 3,
or 4");
}
System.out.print("Enter 0-exit 1-setup 2-list
3-perimeter 4-area: ");
choice = scan.nextInt();
}
/**
* Main method
*/
public static void main(String[] args)
{
System.out.println("Start test run of
calculator.");
TestTriangleV2 obj = new TestTriangleV2();
obj.go();
}
Java for Mathematicians/Page 192
controls.
/**
* listTriPoints displays the (x,y) coordinates of
all three vertices
*/
private void listTriPoints()
{
Point2D.Double a = tri.getPointA();
Point2D.Double b = tri.getPointB();
Point2D.Double c = tri.getPointC();
System.out.println("Triangle");
System.out.printf("Vertex\tx\ty\n");
System.out.printf("%c\t%5.3f\t%5.3f\n", 'A',
a.getX(), a.getY());
System.out.printf("%c\t%5.3f\t%5.3f\n", 'B',
b.getX(), b.getY());
System.out.printf("%c\t%5.3f\t%5.3f\n", 'C',
c.getX(), c.getY());
}
Triangle
Vertex x y
A 0.000 0.000
B 2.500 3.100
C 7.250 8.373
Topic: Exception
from zero to four, but the user typed 2.3, which the
nextInt() was unable to process. The JVM produced an
input-mismatch-exception. The Java 7 API for that
exception is shown next.
The try block acts like a method call. The try block
shown below attempts to execute the following two
commands.
try
{
System.out.print("Enter 0-exit 1-setup 2-list
3-perimeter 4-area: ");
choice = scan.nextInt();
}
/**
* getNextInt get the next int value from the scanner
*/
private int getChoice()
{
int choice = EXIT;
try
{
System.out.print("Enter 0-exit 1-setup 2-list
3-perimeter 4-area: ");
choice = scan.nextInt();
if (choice < EXIT || choice > AREA)
{
System.out.println("Your choice of " +
choice + " is not in the acceptable range of 0 ... 4");
choice = EXIT;
}
}
catch (InputMismatchException ime)
{
System.out.println("Enter only a single digit
number from 0 to 4.");
}
catch (Exception e)
{
Java for Mathematicians/Page 200
/**
* Go method
*/
private void go()
{
int choice = EXIT;
System.out.println("Start test of Triangle
object.");
choice = getChoice();
while (choice != EXIT)
{
switch(choice)
{
case EXIT:
System.out.println("bye");
System.exit(0);
case MAKE:
makeTriangle();
break;
case LIST:
listTriPoints();
break;
case PERIMETER:
System.out.printf("perimeter: %.3f\n",
tri.getPerimeter());
break;
Java for Mathematicians/Page 201
case AREA:
System.out.printf("area: %.3f\n",
tri.getArea());
break;
default:
System.out.println("Enter 0, 1, 2, 3,
or 4");
}
choice = getChoice();
}
import java.util.*;
import java.awt.geom.*;
/**
* Test calculator of triangle facts
*/
Scanner scan;
/**
* Default constructor
*/
public TestTriangleV2()
Java for Mathematicians/Page 205
{
// initialize scanner
scan = new Scanner(System.in);
// Create default triangle
Point2D.Double pointA = new Point2D.Double(0,0);
Point2D.Double pointB = new Point2D.Double(0,1);
Point2D.Double pointC = new Point2D.Double(1,1);
tri = new Triangle(pointA, pointB, pointC);
}
/**
* makePoint sets up a new Point2D.Double
*/
private Point2D.Double makePoint()
{
double x = 0;
double y = 0;
Point2D.Double point = new Point2D.Double(0,0);
System.out.println("Creating new (x,y) point");
System.out.print("Enter x:");
x = scan.nextDouble();
System.out.print("Enter y:");
y = scan.nextDouble();
point = new Point2D.Double(x,y);
return point;
}
/**
* makeTriangle sets up a new triangle.
*/
private void makeTriangle()
{
Point2D.Double a = makePoint();
Java for Mathematicians/Page 206
Point2D.Double b = makePoint();
Point2D.Double c = makePoint();
tri = new Triangle(a,b,c);
}
/**
* listTriPoints displays the (x,y) coordinates of
all three vertices
*/
private void listTriPoints()
{
Point2D.Double a = tri.getPointA();
Point2D.Double b = tri.getPointB();
Point2D.Double c = tri.getPointC();
System.out.println("Triangle");
System.out.printf("Vertex\tx\ty\n");
System.out.printf("%c\t%5.3f\t%5.3f\n", 'A',
a.getX(), a.getY());
System.out.printf("%c\t%5.3f\t%5.3f\n", 'B',
b.getX(), b.getY());
System.out.printf("%c\t%5.3f\t%5.3f\n", 'C',
c.getX(), c.getY());
}
/**
* getNextInt get the next int value from the scanner
*/
private int getChoice()
{
int choice = EXIT;
try
{
System.out.print("Enter 0-exit 1-setup 2-list
Java for Mathematicians/Page 207
/**
* Go method
*/
private void go()
{
int choice = EXIT;
System.out.println("Start test of Triangle
object.");
choice = getChoice();
while (choice != EXIT)
Java for Mathematicians/Page 208
{
switch(choice)
{
case EXIT:
System.out.println("bye");
System.exit(0);
case MAKE:
makeTriangle();
break;
case LIST:
listTriPoints();
break;
case PERIMETER:
System.out.printf("perimeter: %.3f\n",
tri.getPerimeter());
break;
case AREA:
System.out.printf("area: %.3f\n",
tri.getArea());
break;
default:
System.out.println("Enter 0, 1, 2, 3,
or 4");
}
choice = getChoice();
}
/**
* Main method
*/
public static void main(String[] args)
Java for Mathematicians/Page 209
{
System.out.println("Start test run of
calculator.");
TestTriangleV2 obj = new TestTriangleV2();
obj.go();
}
}
Java for Mathematicians/Page 210
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(820, 800);
frame.pack();
frame.setVisible(true);
}
import java.awt.*;
import javax.swing.*;
Java for Mathematicians/Page 214
import java.awt.event.*;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(820, 800);
frame.pack();
frame.setVisible(true);
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
Java for Mathematicians/Page 216
/**
* implements interface ActionListener
*/
// attribute
JButton btn;
/**
* fully parametrized constructor
*
* @param JButton button
*/
public ButtonListener(JButton _btn)
{
btn = _btn;
}
/**
* interface ActionListener requires implementation
of this method
*
* @see java.awt.event.ActionListener
*/
public void actionPerformed(ActionEvent e)
{
btn.setBackground(Color.ORANGE);
}
}
Java for Mathematicians/Page 217
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(820, 800);
frame.pack();
frame.setVisible(true);
Java for Mathematicians/Page 218
import java.awt.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public InnerButtonListener()
{
JPanel panel = new JPanel();
btn = new JButton("push");
panel.add(btn);
ButtonListener btnListener = new
ButtonListener();
btn.addActionListener( btnListener );
add(panel);
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(820, 800);
frame.pack();
frame.setVisible(true);
}
/**
* inner class button listener implements interface
ActionListener
*/
/**
* interface ActionListener requires
implementation of this method
*
* @see java.awt.event.ActionListener
*/
public void actionPerformed(ActionEvent e)
{
btn.setBackground(Color.ORANGE);
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(820, 800);
frame.pack();
frame.setVisible(true);
}
Java for Mathematicians/Page 222
Topic: FlowLayout
Java for Mathematicians/Page 223
import javax.swing.*;
import java.awt.*;
/**
* constructor
*/
public DemoFlowLayout()
{
setTitle("Demo FlowLayout");
setSize(200, 200);
setLocationRelativeTo(null); // Center the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT, 5,
Java for Mathematicians/Page 224
10));
JPanel panel = new JPanel();
panel.setLayout(new
FlowLayout(FlowLayout.LEFT,5,5));
panel.add(new JButton("1"));
panel.add(new JButton("2"));
panel.add(new JButton("3"));
panel.add(new JButton("4"));
panel.add(new JButton("5"));
panel.add(new JButton("6"));
add(panel);
setVisible(true);
}
/**
* main method
*/
public static void main(String[] args)
{
DemoFlowLayout demo = new DemoFlowLayout();
}
}
Java for Mathematicians/Page 225
Topic: BorderLayout
The BorderLayout layout manager divides the screen
into five areas: East, South, West, North, and Center.
To add a new button to the east side of the screen the
command would be add(new JButton(“East”),
BorderLayout.EAST); The component requiring the most
space is usually placed in the center. This java
program demonstrates the use of border layout.
import javax.swing.*;
import java.awt.*;
/**
* constructor
*/
public DemoBorderLayout()
{
setTitle("Demo Border Layout");
setSize(200, 200);
setLocationRelativeTo(null); // Center the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.add(new JButton("west"),
BorderLayout.WEST);
panel.add(new JButton("north"),
BorderLayout.NORTH);
panel.add(new JButton("south"),
BorderLayout.SOUTH);
add(panel);
setVisible(true);
}
/**
* main method
*/
public static void main(String[] args)
{
DemoBorderLayout demo = new DemoBorderLayout();
}
Topic: GridLayout
Java for Mathematicians/Page 227
import javax.swing.*;
import java.awt.*;
/**
* constructor
*/
public DemoGridLayout()
{
setTitle("Demo GridLayout");
setSize(200, 200);
setLocationRelativeTo(null); // Center the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT, 5,
10));
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,2,5,5));
panel.add(new JButton("1"));
panel.add(new JButton("2"));
Java for Mathematicians/Page 228
panel.add(new JButton("3"));
panel.add(new JButton("4"));
panel.add(new JButton("5"));
panel.add(new JButton("6"));
add(panel);
setVisible(true);
}
/**
* main method
*/
public static void main(String[] args)
{
DemoGridLayout demo = new DemoGridLayout();
}
import javax.swing.*;
import java.awt.*;
Java for Mathematicians/Page 230
/**
* Tool for working with triangles
*/
public class TriangleToolV1 extends JFrame
{
/**
* default constructor for triangle tool
*/
public TriangleToolV1()
{
// Set up GUI
setTitle("Triangle Tool");
setSize(800, 600);
setLocationRelativeTo(null); // Center the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/**
* starts the program
*/
private void go()
{
/**
Java for Mathematicians/Page 231
* main method
*/
public static void main(String[] args)
{
TriangleToolV1 tool = new TriangleToolV1();
tool.go();
}
/**
* inner class SketchPanel for drawing triangles,
Java for Mathematicians/Page 232
etc
*/
class SketchPanel extends JPanel
{
/**
* Override JPanel's paintComponent method
*
* @param Graphics object g
*/
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString("triangles will be drawn here",
0, 40);
}
}
import javax.swing.*;
import java.awt.*;
/**
* Tool for working with triangles
*/
public class TriangleToolV2 extends JFrame
{
/**
* default constructor for triangle tool
*/
public TriangleToolV2()
{
// Set up GUI
setTitle("Triangle Tool");
setSize(800, 600);
setLocationRelativeTo(null); // Center the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
/**
* starts the program
*/
private void go()
{
/**
* main method
*/
public static void main(String[] args)
{
TriangleToolV2 tool = new TriangleToolV2();
tool.go();
}
/**
* inner class SketchPanel for drawing triangles,
etc
*/
class SketchPanel extends JPanel
{
Java for Mathematicians/Page 235
/**
* Override JPanel's paintComponent method
*
* @param Graphics object g
*/
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString("triangles will be drawn here",
0, 40);
}
}
import java.awt.geom.*;
import java.awt.*;
/**
* Class CartesianTriangle uses three Points to
describe its triangle.
*/
// Attributes
Point2D.Double pointA, pointB, pointC;
// Constructors
/**
* default constructor
Java for Mathematicians/Page 237
*/
public TriangleCartesian()
{
pointA = new Point2D.Double(); // by default set
to (0,0)
pointB = new Point2D.Double();
pointC = new Point2D.Double();
}
/**
* fully parametrized constructor
*
* @param Point2D.Double three vertices of triangle
*/
public TriangleCartesian(Point2D.Double a,
Point2D.Double b, Point2D.Double c)
{
pointA = a;
pointB = b;
pointC = c;
}
/**
* getPointA returns the Point object for attribute
pointA
*
* @return Point2D.Double for vertex A
*/
public Point2D.Double getPointA()
{
return pointA;
Java for Mathematicians/Page 238
/**
* setPointA sets pointA to the Point provided in
the list of arguments
*
* @param the point for this vertex
*/
public void setPointA(Point2D.Double point)
{
pointA = point;
}
/**
* getPointB returns the Point object for attribute
pointB
*
* @return vertex B
*/
public Point2D.Double getPointB()
{
return pointB;
}
/**
* getPointB sets pointB to the Point provided in
the list of arguments
*
* @param the point for this vertex
*/
public void setPointB(Point2D.Double point)
{
pointB = point;
Java for Mathematicians/Page 239
/**
* getPointC returns the Point object for vertex
pointC
*
* @return vertex C
*/
public Point2D.Double getPointC()
{
return pointC;
}
/**
* getPointA sets pointA to the Point provided in
the list of arguments
*
* @param the point for this vertex
*/
public void setPointC(Point2D.Double point)
{
pointC = point;
}
/**
* get length of side A - B
*/
public double getSideAB()
{
// Point2D.Double extends Point2D which provides
the distance method
return pointA.distance(pointB);
}
Java for Mathematicians/Page 240
/**
* get length of side B-C
*
* @return length of side BC
*/
public double getSideBC()
{
return pointB.distance(pointC);
}
/**
* get length of side A - C
*
* @return length of side AC
*/
public double getSideAC()
{
return pointA.distance(pointC);
}
/**
* get perimeter of triangle
*
* @return perimeter
*/
public double getPerimeter()
{
return getSideAB() + getSideBC() + getSideAC();
}
/**
* calculate area of triangle
Java for Mathematicians/Page 241
/**
* drawTriangle uses a graphics object g to draw
the triangle
*
* @param graphics object
*
* @see java.awt.Polygon
*/
public void drawTriangle(Graphics g)
{
final int SCALE = 10; // Scale by 10 then
truncate to int value for locations
Polygon poly = new Polygon();
Java for Mathematicians/Page 242
poly.addPoint((int)(SCALE * pointA.getX()),
(int)(SCALE * pointA.getY()));
poly.addPoint((int)(SCALE * pointB.getX()),
(int)(SCALE * pointB.getY()));
poly.addPoint((int)(SCALE * pointC.getX()),
(int)(SCALE * pointC.getY()));
g.drawPolygon(poly);
}
/**
* Tool for working with triangles
*/
public class TriangleToolV3 extends JFrame
{
TriangleCartesian triangle;
/**
* default constructor for triangle tool
*/
public TriangleToolV3()
{
// Set up GUI
setTitle("Triangle Tool");
Java for Mathematicians/Page 244
setSize(800, 600);
setLocationRelativeTo(null); // Center the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
/**
* starts the program
*/
private void go()
{
/**
Java for Mathematicians/Page 245
* main method
*/
public static void main(String[] args)
{
TriangleToolV3 tool = new TriangleToolV3();
tool.go();
}
/**
* inner class SketchPanel for drawing triangles,
etc
*/
class SketchPanel extends JPanel
{
/**
* Override JPanel's paintComponent method
*
* @param Graphics object g
*/
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
triangle.drawTriangle(g);
}
}
The class named PointTf holds the text fields for the
x and y coordinates of a single vertex of the
triangle. Since the pair of x and y coordinates for a
vertex represent the coordinates of an object they
should be themselves stored in an object. All those
Java for Mathematicians/Page 248
import javax.swing.*;
import java.awt.geom.*;
/**
* Maintain textFields for the x and y coordinates of a
point
* Always maintain the point and the textfields with
equivalent values
*/
public class PointXYTf
{
JTextField tfX, tfY;
final int JTF_WIDTH = 8;
int jtfWidth;
final String JTF_INIT_VALUE = "0.0";
/**
* Default constructor
*/
public PointXYTf()
{
jtfWidth = JTF_WIDTH;
/**
* fully parametrized constructor using JTextFields
*/
public PointXYTf(JTextField tfx, JTextField tfy)
{
tfX = tfx;
tfY = tfy;
}
/**
* fully parametrized constructor using Point2D.Double
*
* @param Point2D.Double the point matching these
text fields
*/
public PointXYTf(Point2D.Double pt)
{
// point = pt;
double x = pt.getX();
String xStr = new Double(x).toString();
tfX = new JTextField(xStr);
double y = pt.getY();
String yStr = new Double(y).toString();
tfY = new JTextField(yStr);
}
/**
* Set contents of tfX and tfY for point
*
* @param Point2D.Double point matching these text
fields
Java for Mathematicians/Page 250
*/
public void setTfXY(Point2D.Double p)
{
double x = p.getX();
Double dX = new Double(x);
String xString = dX.toString();
tfX.setText(xString);
double y = p.getY();
Double dY = new Double(y);
String yString = dY.toString();
tfY.setText(yString);
}
/**
* Set x value
*
* @param double x coordinate
*/
public void setTfX(double x)
{
Double dX = new Double(x);
String xString = dX.toString();
tfX.setText(xString);
}
/**
* Set y value
*
* @param double y coordinate
*/
public void setTfY(double y)
{
Double dY = new Double(y);
Java for Mathematicians/Page 251
/**
* Get textfield X
*
* @return JTextField for X coordinate
*/
public JTextField getTfX()
{
return tfX;
}
/**
* Get textfield Y
*
* @return JTextField for Y coordinate
*/
public JTextField getTfY()
{
return tfY;
}
/**
* return Point2D.Double
*
* @return Point2D with X,Y coordinates
*/
public Point2D.Double getPoint2D()
{
String strX = tfX.getText();
double x = new Double(strX).doubleValue();
Java for Mathematicians/Page 252
/**
* toString method
*
* @return description of x,y coordinates
*/
public String toString()
{
return "[" + tfX.getText() + "," + tfY.getText()
+"]";
}
}
Notice the PointXYTf class can return the vertex as a
Point 2D.Double object which satisfies the
requirements of the Polygon class. So these classes
cooperate well.
results.add(jtfArea);
results.add(new JLabel("perimeter"));
jtfPerimeter = new JTextField(8);
jtfPerimeter.setText("0.0");
results.add(jtfPerimeter);
perimeter = 0;
dataPanel.add(results, BorderLayout.SOUTH);
1 import javax.swing.*;
2 import java.awt.*;
3 import java.awt.event.*;
4 import java.awt.geom.*;
5 import java.util.*;
6
7 /**
8 * Tool for working with triangles
9 */
10 public class TriangleToolV4 extends JFrame
11 {
12 TriangleCartesian triangle;
13 ArrayList<PointXYTf> trianglePointsTf;
14 JTextField jtfArea, jtfPerimeter;
15 double area, perimeter;
16
17 /**
18 * default constructor for triangle tool
19 */
20 public TriangleToolV4()
21 {
22 // Set up GUI
23 setTitle("Triangle Tool");
24 setSize(800, 600);
25 setLocationRelativeTo(null); // Center the
frame
Java for Mathematicians/Page 255
26
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
27 //Set BorderLayout with horizontal gap 5 and
vertical gap 10
28 setLayout(new BorderLayout(5, 10));
29
30 // Add sketch pad to draw triangle
31 JPanel sketchPad = new SketchPanel();
32 // sketchPad.add(new JLabel("sketch pad"));
33 add(sketchPad, BorderLayout.CENTER);
34
35 // Create data panel for points and results
at right (EAST) side
36 JPanel dataPanel = new JPanel();
37 dataPanel.setLayout(new BorderLayout(5, 10));
38
39 // Add x,y addresses of three defining
points of triangle
40 JPanel triangleTfGrid = new JPanel();
41 triangleTfGrid.setLayout(new GridLayout(4,
2, 5, 5));
42 triangleTfGrid.add(new JLabel("x"));
43 triangleTfGrid.add(new JLabel("y"));
44 // Add 2 x 3 array of JTextField
45 trianglePointsTf = new
ArrayList<PointXYTf>();
46 final int VERTEX_CNT = 3;
47
48 for (int i = 0; i < VERTEX_CNT; i++)
49 {
50 PointXYTf ptTf = new PointXYTf(new
Point2D.Double(0,0));
51 trianglePointsTf.add(ptTf);
Java for Mathematicians/Page 256
52 triangleTfGrid.add(ptTf.getTfX());
53 triangleTfGrid.add(ptTf.getTfY());
54 }
55 dataPanel.add(triangleTfGrid,
BorderLayout.NORTH);
56
57 // Add 2 x 2 array of calculated results
58 JPanel results = new JPanel();
59 results.setLayout(new GridLayout(2, 2, 5,
5));
60 results.add(new JLabel("area"));
61 jtfArea = new JTextField(8);
62 jtfArea.setText("0.0");
63 area = 0;
64 results.add(jtfArea);
65 results.add(new JLabel("perimeter"));
66 jtfPerimeter = new JTextField(8);
67 jtfPerimeter.setText("0.0");
68 results.add(jtfPerimeter);
69 perimeter = 0;
70 dataPanel.add(results, BorderLayout.SOUTH);
71
72 add(dataPanel, BorderLayout.EAST);
73
74 // Add control panel to the bottom (SOUTH)
of the window
75 JPanel controls = new JPanel();
76 controls.setLayout(new
FlowLayout(FlowLayout.LEFT, 10, 20));
77 JButton jbtnCalc = new JButton("calculate");
78 jbtnCalc.addActionListener(
79 new ActionListener()
80 {
Java for Mathematicians/Page 257
81 public void
actionPerformed(ActionEvent e)
82 {
83 calcTriangle();
84 repaint();
85 }
86 }
87 );
88 controls.add(jbtnCalc);
89 add(controls, BorderLayout.SOUTH);
90 triangle = new TriangleCartesian();
91 setVisible(true);
92 }
93
94 /**
95 * Calculate triangle's area and perimeter
96 */
97 private void calcTriangle()
98 {
99 Point2D.Double a, b, c;
100 System.out.println("Starting calcTriangle");
101 ArrayList<Point2D.Double> vertices = new
ArrayList<>();
102 for (PointXYTf row : trianglePointsTf)
103 {
104 System.out.println(row);
105 vertices.add(row.getPoint2D());
106 }
107 System.out.println("number of points: " +
vertices.size());
108 a = vertices.get(0);
109 b = vertices.get(1);
110 c = vertices.get(2);
Java for Mathematicians/Page 258
111 triangle =
112 new TriangleCartesian(a, b, c);
113 area = triangle.getArea();
114 String areaStr = String.format("%8.3f",
area);
115 jtfArea.setText(areaStr);
116 perimeter = triangle.getPerimeter();
117 String perimeterStr = String.format("%8.3f",
perimeter);
118 jtfPerimeter.setText(perimeterStr);
119 }
120
121
122 /**
123 * starts the program
124 */
125 private void go()
126 {
127
128 }
129
130 /**
131 * main method
132 */
133 public static void main(String[] args)
134 {
135 TriangleToolV4 tool = new TriangleToolV4();
136 tool.go();
137 }
138
139 /**
140 * inner class SketchPanel for drawing
triangles, etc
Java for Mathematicians/Page 259
141 */
142 class SketchPanel extends JPanel
143 {
144
145 /**
146 * Override JPanel's paintComponent method
147 *
148 * @param Graphics object g
149 */
150 protected void paintComponent(Graphics g)
151 {
152 super.paintComponent(g);
153 triangle.drawTriangle(g);
154 }
155 }
156
157 } // end class TriangleTool