![]() |
||
Select a Chapter:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Back to the Main Page
|
||
| Chapter Eleven listings: 9 classes | ||
import javax.swing.JOptionPane;
/** Add up all Fraction values given on the command line.
* Print the total and the smallest one entered. */
public class AddFractions
{
public static void main (String[] args)
{ String response = "No values entered."; // just in case
if (args != null && args.length > 0)
try
{ Numeric total = Fraction.ZERO.valueOf (args[0]);
Numeric smallestSoFar = total;
for (int k = 1; k < args.length; k++)
{ Numeric data = total.valueOf (args[k]);
total = total.add (data);
if (smallestSoFar.compareTo (data) > 0)
smallestSoFar = data;
}
response = "total = " + total.toString()
+ "; smallest = " + smallestSoFar.toString();
}catch (RuntimeException e)
{ response = "Some entry was not fractional.";
}
JOptionPane.showMessageDialog (null, response);
System.exit (0);
} //======================
}
import java.io.BufferedReader;
public abstract class Numeric implements Comparable
{
/** Convert to the appropriate subclass. Return null if par is
* null or "". Throw NumberFormatException if wrong form. */
public abstract Numeric valueOf (String par);
/** Convert to string form. */
public abstract String toString();
/** Convert to a real-number equivalent. */
public abstract double doubleValue();
/** Tell whether the executor equals the parameter. */
public abstract boolean equals (Object ob);
/** Like String's compareTo: a positive means ob is "smaller".
* Throw NullPointerException if ob is null.
* Throw ClassCastException if ob is not the same type. */
public abstract int compareTo (Object ob);
/** Return a new Numeric that is the sum of both.
* Return null if they are the same subtype but the answer
* is not computable. Throw an Exception if par is null or
* the executor and par are different subtypes. */
public abstract Numeric add (Numeric par);
/** Same as add, except return executor minus par. */
public abstract Numeric subtract (Numeric par);
/** Same as add, except return executor times par. */
public abstract Numeric multiply (Numeric par);
/** Return the larger of the two Numeric values. Throw an
* Exception if they are not both non-null values of the
* same Numeric type.*/
public static Numeric max (Numeric data, Numeric other)
{ return (data.compareTo (other) > 0) ? data : other;
} //======================
/** Return the square of the executor. */
public Numeric square()
{ return this.multiply (this);
} //======================
/** Read Numeric values from the BufferedReader and add them
* to the executor, until null is seen or until a value
* cannot be added to the executor. Return the total. */
public Numeric addMore (BufferedReader source)
{ Numeric total = this;
try
{ Numeric data = this.valueOf (source.readLine());
while (data != null && total != null)
{ total = total.add (data);
data = this.valueOf (source.readLine());
}
}catch (Exception e)
{ // no need for any statements here; just return total
}
return total;
} //======================
}
public abstract class BasicGame
{
public final void playManyGames()
{ playOneGame();
while (javax.swing.JOptionPane.showConfirmDialog (null,
"again?") == javax.swing.JOptionPane.YES_OPTION)
playOneGame();
} //======================
public final void playOneGame()
{ askUsersFirstChoice();
while (shouldContinue())
{ showUpdatedStatus();
askUsersNextChoice();
}
showFinalStatus();
} //======================
public abstract void askUsersFirstChoice();
public abstract boolean shouldContinue();
public abstract void showUpdatedStatus();
public abstract void askUsersNextChoice();
public void showFinalStatus()
{ javax.swing.JOptionPane.showMessageDialog (null,
"That was right. \nCongratulations.");
} //======================
}
public class Fraction extends Numeric
{
/** A constant representing ZERO. */
public static final Fraction ZERO = new Fraction (0, 1);
/////////////////////////////////
private int itsUpper; // the numerator of the fraction
private int itsLower; // the denominator of the fraction
/** Construct a Fraction from the given two integers. */
public Fraction (int numerator, int denominator)
{ if (numerator == 0 || denominator == 0)
{ itsUpper = 0;
itsLower = 1;
}
else if (denominator < 0)
{ itsUpper = - numerator;
itsLower = - denominator;
this.reduceToLowestTerms();
}
else
{ itsUpper = numerator;
itsLower = denominator;
this.reduceToLowestTerms();
}
} //======================
/** The parameter should be two ints separated by '/', e.g.
* "2/3". Return null if par is null or "". Otherwise
* throw a NumberFormatException if the wrong form. */
public Numeric valueOf (String par)
{ if (par == null || par.length() == 0)
return null;
int k = 0;
while (k < par.length() - 1 && par.charAt (k) != '/')
k++;
return new Fraction
(Integer.parseInt (par.substring (0, k)),
Integer.parseInt (par.substring (k + 1)));
} //======================
/** Express the Fraction as a String, e.g., "2/3". */
public String toString()
{ return this.itsUpper + "/" + this.itsLower;
} //======================
/** Tell whether the two Fraction objects are equal. */
public boolean equals (Object ob)
{ return ob instanceof Fraction
&& ((Fraction) ob).itsUpper == this.itsUpper
&& ((Fraction) ob).itsLower == this.itsLower;
} //======================
/** Return the sum of the executor and par. */
public Numeric add (Numeric par)
{ Fraction that = (Fraction) par; // for simplicity
return new Fraction (this.itsUpper * that.itsLower
+ this.itsLower * that.itsUpper,
this.itsLower * that.itsLower);
} //======================
/** Return the approximate value as a double value. */
public double doubleValue()
{ return itsUpper * 1.0 / itsLower;
} //======================
/** Reduce the fraction to lowest terms. Precondition: the
* denominator is positive and the numerator is non-zero. */
private Fraction reduceToLowestTerms()
{ divideOut (2);
int limit = Math.min (Math.abs (itsUpper), itsLower);
for (int divider = 3; divider <= limit; divider += 2)
divideOut (divider);
return this;
} //======================
private void divideOut (int divider)
{ while (itsUpper % divider == 0 && itsLower % divider == 0)
{ itsUpper /= divider;
itsLower /= divider;
}
} //======================
public int compareTo (Object ob)
// Return the numerator of the result of subtracting this minus ob:
{ return this.itsUpper * ((Fraction) ob).itsLower
- this.itsLower * ((Fraction) ob).itsUpper;
} //======================
public Numeric subtract (Numeric par) { return null; }
public Numeric multiply (Numeric par) { return null; }
}
public class Complex extends Numeric
{
public static final Complex ZERO = new Complex (0, 0);
/////////////////////////////////
private final double itsReal;
private final double itsImag;
public Complex (double realPart, double imagPart)
{ itsReal = realPart;
itsImag = imagPart;
} //======================
public String toString ()
{ String operator = itsImag < 0 ? " " : " +";
return itsReal + operator + itsImag + "i";
} //======================
public double doubleValue()
{ return itsReal;
} //======================
public int compareTo (Object ob)
{ double diff = this.itsReal - ((Complex) ob).itsReal;
if (diff == 0)
return 0;
else
return (diff > 0) ? 1 : -1;
} //======================
public Numeric add (Numeric par)
{ Complex that = (Complex) par;
return new Complex (this.itsReal + that.itsReal,
this.itsImag + that.itsImag);
} //======================
// the following are left as exercises
public boolean equals (Object ob)
{ return ob instanceof Complex
&& ((Complex) ob).itsReal == this.itsReal
&& ((Complex) ob).itsImag == this.itsImag;
} //======================
public Numeric multiply (Numeric par)
{ Complex that = (Complex) par;
return new Complex (this.itsReal * that.itsReal
- this.itsImag * that.itsImag,
this.itsReal * that.itsImag
+ this.itsImag * that.itsReal);
} //======================
public Numeric subtract (Numeric par) {return ZERO;}
public Numeric valueOf (String par) {return ZERO;}
}
public class VeryLong extends Numeric
{
public static final VeryLong ZERO = new VeryLong (0, 0, 0);
private static final int BILLION = 1000000000;
private static final long LONGBILL = 1000000000L;
private static final int MAX = 6;
/////////////////////////////////
private final int[] itsItem = new int[MAX]; // all zeros
public VeryLong (long left, long mid, long right)
{ this.itsItem[0] = (int) (left / LONGBILL);
this.itsItem[1] = (int) (left % LONGBILL);
this.itsItem[2] = (int) (mid / LONGBILL);
this.itsItem[3] = (int) (mid % LONGBILL);
this.itsItem[4] = (int) (right / LONGBILL);
this.itsItem[5] = (int) (right % LONGBILL);
} //======================
public String toString ()
{ String s = "" + itsItem[0];
for (int k = 1; k < MAX; k++)
s += "," + ((BILLION + itsItem[k]) + "").substring(1);
return s;
} //======================
public Numeric add (Numeric par)
{ VeryLong that = (VeryLong) par;
VeryLong result = new VeryLong();
for (int k = 0; k < MAX; k++)
result.itsItem[k] = this.itsItem[k] + that.itsItem[k];
for (int k = MAX - 1; k > 0; k--)
{ if (result.itsItem[k] >= BILLION)
{ result.itsItem[k] -= BILLION;
result.itsItem[k - 1]++;
}
}
return result.itsItem[0] >= BILLION ? null : result;
} //======================
private VeryLong() // only used by other VeryLong methods
{
} //======================
public double doubleValue()
{ double total = itsItem[0];
for (int k = 1; k < MAX; k++)
total = total * BILLION + itsItem[k];
return total;
} //======================
public boolean equals (Object ob)
{ if (! (ob instanceof VeryLong))
return false;
VeryLong that = (VeryLong) ob;
for (int k = 0; k < MAX; k++)
{ if (this.itsItem[k] != that.itsItem[k])
return false;
}
return true;
} //======================
public Numeric subtract (Numeric par) {return ZERO;}
public Numeric valueOf (String par) {return ZERO;}
public int compareTo (Object ob) {return 0; }
public Numeric multiply (Numeric par) {return ZERO;}
}
/** Precondition: if n is the number of values, they are
* stored in components 0...n-1 and the other components
* are null, and 0 <= n < length of array. */
public class NumericArray
{
/** Tell whether target is a non-null value in the array. */
public static boolean find (Object[ ] item, Object target)
{ for (int k = 0; item[k] != null; k++)
{ if (item[k].equals (target))
return true;
}
return false;
} //======================
/** Return the sum of the values in the array; return null
* if the sum is not computable. Precondition:
* All non-null values are of the same Numeric type. */
public static Numeric sum (Numeric[ ] item)
{ if (item[0] == null)
return null;
Numeric total = item[0];
for (int k = 1; item[k] != null && total != null; k++)
total = total.add (item[k]);
return total;
} //======================
/** Print each non-null value on the screen. */
public static void display (Object[ ] item)
{ for (int k = 0; item[k] != null; k++)
System.out.println (item[k].toString());
} //======================
/** Return the array of values read from the source, to a
* maximum of limit values. Precondition: limit >= 0 and
* data is the same Numeric subtype as all input values. */
public static Numeric[ ] getInput (Numeric data, int limit,
java.io.BufferedReader source)
throws java.io.IOException
{ Numeric[ ] item = new Numeric [limit + 1]; // all nulls
for (int k = 0; k < limit; k++)
{ item[k] = data.valueOf (source.readLine());
if (item[k] == null)
return item;
}
return item;
} //======================
// the following are from the exercises
public static double sumValues (Numeric[ ] item)
{ double valueToReturn = 0;
for (int k = 0; item[k] != null; k++)
valueToReturn += item[k].doubleValue();
return valueToReturn;
} //======================
public static int size (Object [ ] item)
{ int k = 0;
while (item[k] != null)
k++;
return k;
} //======================
public static boolean allSmall (Numeric[ ] item, Numeric par)
{ for (int k = 0; item[k] != null; k++)
{ if (item[k].compareTo (par) >= 0)
return false;
}
return true;
} //======================
public static int indexSmallest (Numeric[ ] item)
{ int valueToReturn = 0;
for (int k = 1; item[k] != null; k++)
{ if (item[k].compareTo (item[valueToReturn]) < 0)
valueToReturn = k;
}
return valueToReturn;
} //======================
public static void delete (Object[ ] item, int n)
{ if (n >= 0 && n < item.length)
{ for ( ; item[n] != null; n++)
item[n] = item[n + 1];
}
} //======================
public static Numeric[] getComplexes (Numeric[ ] item)
{ Numeric[ ] valueToReturn = new Numeric [item.length];
int next = 0;
for (int k = 0; item[k] != null; k++)
{ if (item[k] instanceof Complex)
{ valueToReturn[next] = item[k];
next++;
}
}
return valueToReturn;
} //======================
}
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
public class AddFromFile
{
/** Read in up to 100 Fraction values from a file,
* then display them all on the screen with their sum. */
public static void main (String[ ] args) throws IOException
{ Numeric [ ] values = NumericArray.getInput
(Fraction.ZERO, 100, new BufferedReader
(new FileReader ("numeric.dat")));
NumericArray.display (values);
System.out.println ("Their sum is "
+ NumericArray.sum (values));
} //======================
}
public class ThreadOp
{
public static boolean pause (int millis)
{ try
{ Thread.sleep (millis);
return Thread.interrupted();
}
catch (InterruptedException e)
{ return true;
}
} //======================
}
|
Layout and Design Copyright © Psumonix, LLC. All Rights Reserved. |