JAVA:
An Introduction to Problem Solving & Programming, 7th
Ed. By Walter Savitch.
ISBN 0133862119 ©
2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Listing 7.1 |
/** Reads 7 temperatures from the user and shows which are above and which are below the average of the 7 temperatures. */ import java.util.Scanner; public class ArrayOfTemperatures { public static void main (String [] args) { double [] temperature = new double [7]; // Read temperatures and compute their average: Scanner keyboard = new Scanner (System.in); System.out.println ("Enter 7 temperatures:"); double sum = 0; for (int index = 0 ; index < 7 ; index++) { temperature [index] = keyboard.nextDouble (); sum = sum + temperature [index]; } double average = sum / 7; System.out.println ("The average temperature is " + average); // Display each temperature and its relation to the average: System.out.println ("The temperatures are"); for (int index = 0 ; index < 7 ; index++) { if (temperature [index] < average) System.out.println (temperature [index] + " below average."); else if (temperature [index] > average) System.out.println (temperature [index] + " above average."); else //temperature[index] == average System.out.println (temperature [index] + " the average."); } System.out.println ("Have a nice week."); } } |
Listing 7.2 |
/** Reads temperatures from the user and shows which are above and which are below the average of all the temperatures. */ import java.util.Scanner; public class ArrayOfTemperatures2 { public static void main (String [] args) { Scanner keyboard = new Scanner (System.in); System.out.println ("How many temperatures do you have?"); int size = keyboard.nextInt (); double [] temperature = new double [size]; // Read temperatures and compute their average: System.out.println ("Enter " + temperature.length + " temperatures:"); double sum = 0; for (int index = 0 ; index < temperature.length ; index++) { temperature [index] = keyboard.nextDouble (); sum = sum + temperature [index]; } double average = sum / temperature.length; System.out.println ("The average temperature is " + average); // Display each temperature and its relation to the average: System.out.println ("The temperatures are"); for (int index = 0 ; index < temperature.length ; index++) { if (temperature [index] < average) System.out.println (temperature [index] + " below average."); else if (temperature [index] > average) System.out.println (temperature [index] + " above average."); else //temperature[index] == average System.out.println (temperature [index] + " the average."); } System.out.println ("Have a nice week."); } } |
Listing 7.3 |
import java.util.Scanner; /** Class for sales associate records. */ public class SalesAssociate { private String name; private double sales; public SalesAssociate () { name = "No record"; sales = 0; } public SalesAssociate (String initialName, double initialSales) { set (initialName, initialSales); } public void set (String newName, double newSales) { name = newName; sales = newSales; } public void readInput () { System.out.print ("Enter name of sales associate: "); Scanner keyboard = new Scanner (System.in); name = keyboard.nextLine (); System.out.print ("Enter associates sales: $"); sales = keyboard.nextDouble (); } public void writeOutput () { System.out.println ("Name: " + name); System.out.println ("Sales: $" + sales); } public String getName () { return name; } public double getSales () { return sales; } } |
Listing 7.4 |
import java.util.Scanner; /** Program to generate sales report. */ public class SalesReporter { private double highestSales; private double averageSales; private SalesAssociate [] team; //The array object is //created in getData. private int numberOfAssociates; //Same as team.length /** Reads the number of sales associates and data for each one. */ public void getData () { Scanner keyboard = new Scanner (System.in); System.out.println ("Enter number of sales associates:"); numberOfAssociates = keyboard.nextInt (); team = new SalesAssociate [numberOfAssociates + 1]; for (int i = 1 ; i <= numberOfAssociates ; i++) { team [i] = new SalesAssociate (); System.out.println ("Enter data for associate " + i); team [i].readInput (); System.out.println (); } } /** Computes the average and highest sales figures. Precondition: There is at least one salesAssociate. */ public void computeStats () { double nextSales = team [1].getSales (); highestSales = nextSales; double sum = nextSales; for (int i = 2 ; i <= numberOfAssociates ; i++) { nextSales = team [i].getSales (); sum = sum + nextSales; if (nextSales > highestSales) highestSales = nextSales; //highest sales so far. } averageSales = sum / numberOfAssociates; } /** Displays sales report on the screen. */ public void displayResults () { System.out.println ("Average sales per associate is $" + averageSales); System.out.println ("The highest sales figure is $" + highestSales); System.out.println (); System.out.println ("The following had the highest sales:"); for (int i = 1 ; i <= numberOfAssociates ; i++) { double nextSales = team [i].getSales (); if (nextSales == highestSales) { team [i].writeOutput (); System.out.println ("$" + (nextSales - averageSales) + " above the average."); System.out.println (); } } System.out.println ("The rest performed as follows:"); for (int i = 1 ; i <= numberOfAssociates ; i++) { double nextSales = team [i].getSales (); if (team [i].getSales () != highestSales) { team [i].writeOutput (); if (nextSales >= averageSales) System.out.println ("$" + (nextSales - averageSales) + " above the average."); else System.out.println ("$" + (averageSales - nextSales) + " below the average."); System.out.println (); } } } public static void main (String [] args) { SalesReporter clerk = new SalesReporter (); clerk.getData (); clerk.computeStats (); clerk.displayResults (); } } |
Listing 7.5 |
import java.util.Scanner; /** A demonstration of using indexed variables as arguments. */ public class ArgumentDemo { public static void main (String [] args) { Scanner keyboard = new Scanner (System.in); System.out.println ("Enter your score on exam 1:"); int firstScore = keyboard.nextInt (); int [] nextScore = new int [3]; for (int i = 0 ; i < nextScore.length ; i++) nextScore [i] = firstScore + 5 * i; for (int i = 0 ; i < nextScore.length ; i++) { double possibleAverage = getAverage (firstScore, nextScore [i]); System.out.println ("If your score on exam 2 is " + nextScore [i]); System.out.println ("your average will be " + possibleAverage); } } public static double getAverage (int n1, int n2) { return (n1 + n2) / 2.0; } } |
Listing 7.6 |
/** A demonstration program to test two arrays for equality. */ public class TestEquals { public static void main (String [] args) { int [] a = new int [3]; int [] b = new int [3]; setArray (a); setArray (b); if (b == a) System.out.println ("Equal by ==."); else System.out.println ("Not equal by ==."); if (equals (b, a)) System.out.println ("Equal by the equals method."); else System.out.println ("Not equal by the equals method."); } public static boolean equals (int [] a, int [] b) { boolean elementsMatch = true; //tentatively if (a.length != b.length) elementsMatch = false; else { int i = 0; while (elementsMatch && (i < a.length)) { if (a [i] != b [i]) elementsMatch = false; i++; } } return elementsMatch; } public static void setArray (int [] array) { for (int i = 0 ; i < array.length ; i++) array [i] = i; } } |
Listing 7.7 |
import java.util.Scanner; /** A demonstration of a method that returns an array. */ public class ReturnArrayDemo { public static void main (String [] args) { Scanner keyboard = new Scanner (System.in); System.out.println ("Enter your score on exam 1:"); int firstScore = keyboard.nextInt (); int [] nextScore = new int [3]; for (int i = 0 ; i < nextScore.length ; i++) nextScore [i] = firstScore + 5 * i; double [] averageScore = getArrayOfAverages (firstScore, nextScore); for (int i = 0 ; i < nextScore.length ; i++) { System.out.println ("If your score on exam 2 is " + nextScore [i]); System.out.println ("your average will be " + averageScore [i]); } } public static double [] getArrayOfAverages (int firstScore, int [] nextScore) { double [] temp = new double [nextScore.length]; for (int i = 0 ; i < temp.length ; i++) temp [i] = getAverage (firstScore, nextScore [i]); return temp; } public static double getAverage (int n1, int n2) { return (n1 + n2) / 2.0; } } |
Listing 7.8 |
import java.util.Scanner; public class ListDemo { public static final int MAX_SIZE = 3; //Assumed > 0 public static void main (String [] args) { OneWayNoRepeatsList toDoList = new OneWayNoRepeatsList (MAX_SIZE); System.out.println ( "Enter items for the list, when prompted."); boolean moreEntries = true; String next = null; Scanner keyboard = new Scanner (System.in); while (moreEntries && !toDoList.isFull ()) { System.out.println ("Enter an item:"); next = keyboard.nextLine (); toDoList.addItem (next); if (toDoList.isFull ()) { System.out.println ("List is now full."); } else { System.out.print ("More items for the list? "); String ans = keyboard.nextLine (); if (ans.trim ().equalsIgnoreCase ("no")) moreEntries = false; //User says no more } } System.out.println ("The list contains:"); int position = toDoList.START_POSITION; next = toDoList.getEntryAt (position); while (next != null) //null indicates end of list { System.out.println (next); position++; next = toDoList.getEntryAt (position); } } } |
Listing 7.9 |
/** An object of this class is a special kind of list of strings. You can write the list only from beginning to end. You can add only to the end of the list. You cannot change individual entries, but you can erase the entire list and start over. No entry may appear more than once on the list. You can use int variables as position markers into the list. Position markers are similar to array indices, but are numbered starting with 1. */ public class OneWayNoRepeatsList { public static int START_POSITION = 1; public static int DEFAULT_SIZE = 50; //entry.length is the total number of items you have room //for on the list (its capacity); countOfEntries is the number of //items currently on the list. private int countOfEntries; //can be less than entry.length. private String [] entry; /** Creates an empty list with a given capacity. */ public OneWayNoRepeatsList (int maximumNumberOfEntries) { entry = new String [maximumNumberOfEntries]; countOfEntries = 0; } /** Creates an empty list with a capacity of DEFAULT_SIZE. */ public OneWayNoRepeatsList () { entry = new String [DEFAULT_SIZE]; countOfEntries = 0; // or replace these two statements with this(DEFAULT_SIZE); } public boolean isFull () { return countOfEntries == entry.length; } public boolean isEmpty () { return countOfEntries == 0; } /** Precondition: List is not full. Postcondition: If item was not on the list, it has been added to the list. */ public void addItem (String item) { if (!isOnList (item)) { if (countOfEntries == entry.length) { System.out.println ("Adding to a full list!"); System.exit (0); } else { entry [countOfEntries] = item; countOfEntries++; } } //else do nothing. Item is already on the list. } /** If the argument indicates a position on the list, the entry at that specified position is returned; otherwise, null is returned. */ public String getEntryAt (int position) { String result = null; if ((1 <= position) && (position <= countOfEntries)) result = entry [position - 1]; return result; } /** Returns true if position indicates the last item on the list; otherwise, returns false. */ public boolean atLastEntry (int position) { return position == countOfEntries; } /** Returns true if item is on the list; otherwise, returns false. Does not differentiate between uppercase and lowercase letters. */ public boolean isOnList (String item) { boolean found = false; int i = 0; while (!found && (i < countOfEntries)) { if (item.equalsIgnoreCase (entry [i])) found = true; else i++; } return found; } public int getMaximumNumberOfEntries () { return entry.length; } public int getNumberOfEntries () { return countOfEntries; } public void eraseList () { countOfEntries = 0; } } |
Listing 7.10 |
/** Class for sorting an array of base type int from smallest to largest. */ public class ArraySorter { /** Precondition: Every element in anArray has a value. Action: Sorts the array into ascending order. */ public static void selectionSort (int [] anArray) { for (int index = 0 ; index < anArray.length - 1 ; index++) { // Place the correct value in anArray[index] int indexOfNextSmallest = getIndexOfSmallest (index, anArray); interchange (index, indexOfNextSmallest, anArray); //Assertion:anArray[0] <= anArray[1] <=...<= anArray[index] //and these are the smallest of the original array elements. //The remaining positions contain the rest of the original //array elements. } } /** Returns the index of the smallest value in the portion of the array that begins at the element whose index is startIndex and ends at the last element. */ private static int getIndexOfSmallest (int startIndex, int [] a) { int min = a [startIndex]; int indexOfMin = startIndex; for (int index = startIndex + 1 ; index < a.length ; index++) { if (a [index] < min) { min = a [index]; indexOfMin = index; //min is smallest of a[startIndex] through a[index] } } return indexOfMin; } /** Precondition: i and j are valid indices for the array a. Postcondition: Values of a[i] and a[j] have been interchanged. */ private static void interchange (int i, int j, int [] a) { int temp = a [i]; a [i] = a [j]; a [j] = temp; //original value of a[i] } } |
Listing 7.11 |
public class SelectionSortDemo
{
public static void main (String [] args)
{
int [] b = {7, 5, 11, 2, 16, 4, 18, 14, 12, 30};
display (b, before);
ArraySorter.selectionSort (b);
display (b, after);
}
public static void display (int [] array, String when)
{
System.out.println ("Array values " + when + " sorting:");
for (int i = 0 ; i < array.length ; i++)
System.out.print (array [i] + " ");
System.out.println ();
}
}
|
Listing 7.12 |
/** Displays a two-dimensional table showing how interest rates affect bank balances. */ public class InterestTable { public static void main (String [] args) { int [] [] table = new int [10] [6]; for (int row = 0 ; row < 10 ; row++) for (int column = 0 ; column < 6 ; column++) table [row] [column] = getBalance (1000.00, row + 1, (5 + 0.5 * column)); System.out.println ("Balances for Various Interest Rates " + "Compounded Annually"); System.out.println ("(Rounded to Whole Dollar Amounts)"); System.out.println (); System.out.println ("Years 5.00% 5.50% 6.00% 6.50% 7.00% 7.50%"); for (int row = 0 ; row < 10 ; row++) { System.out.print ((row + 1) + " "); for (int column = 0 ; column < 6 ; column++) System.out.print ("$" + table [row] [column] + " "); System.out.println (); } } /** Returns the balance in an account after a given number of years and interest rate with an initial balance of startBalance. Interest is compounded annually. The balance is rounded to a whole number. */ public static int getBalance (double startBalance, int years, double rate) { double runningBalance = startBalance; for (int count = 1 ; count <= years ; count++) runningBalance = runningBalance * (1 + rate / 100); return (int) (Math.round (runningBalance)); } } |
Listing 7.13 |
/** Displays a two-dimensional table showing how interest rates affect bank balances. */ public class InterestTable2 { public static final int ROWS = 10; public static final int COLUMNS = 6; public static void main (String [] args) { int [] [] table = new int [ROWS] [COLUMNS]; for (int row = 0 ; row < ROWS ; row++) for (int column = 0 ; column < COLUMNS ; column++) table [row] [column] = getBalance (1000.00, row + 1, (5 + 0.5 * column)); System.out.println ("Balances for Various Interest Rates " + "Compounded Annually"); System.out.println ("(Rounded to Whole Dollar Amounts)"); System.out.println (); System.out.println ("Years 5.00% 5.50% 6.00% 6.50% 7.00% 7.50%"); showTable (table); } /** Precondition: The array anArray has ROWS rows and COLUMNS columns. Postcondition: The array contents are displayed with dollar signs. */ public static void showTable (int [] [] anArray) { for (int row = 0 ; row < ROWS ; row++) { System.out.print ((row + 1) + " "); for (int column = 0 ; column < COLUMNS ; column++) System.out.print ("$" + anArray [row] [column] + " "); System.out.println (); } } public static int getBalance (double startBalance, int years, double rate) { double runningBalance = startBalance; for (int count = 1 ; count <= years ; count++) runningBalance = runningBalance * (1 + rate / 100); return (int) (Math.round (runningBalance)); } } |
Listing 7.14 |
/** Class that records the time worked by each of a companys employees during one five-day week. A sample application is in the main method. */ public class TimeBook { private int numberOfEmployees; private int [] [] hours; //hours[i][j] has the hours for //employee j on day i. private int [] weekHours; //weekHours[i] has the weeks //hours worked for employee i + 1. private int [] dayHours; //dayHours[i] has the total hours //worked by all employees on day i. private static final int NUMBER_OF_WORKDAYS = 5; private static final int MON = 0; private static final int TUE = 1; private static final int WED = 2; private static final int THU = 3; private static final int FRI = 4; /** Reads hours worked for each employee on each day of the work week into the two-dimensional array hours. (The method for input is just a stub in this preliminary version.) Computes the total weekly hours for each employee and the total daily hours for all employees combined. */ public static void main (String [] args) { private static final int NUMBER_OF_EMPLOYEES = 3; TimeBook book = new TimeBook (NUMBER_OF_EMPLOYEES); book.setHours (); book.update (); book.showTable (); } public TimeBook (int theNumberOfEmployees) { numberOfEmployees = theNumberOfEmployees; hours = new int [NUMBER_OF_WORKDAYS] [numberOfEmployees]; weekHours = new int [numberOfEmployees]; dayHours = new int [NUMBER_OF_WORKDAYS]; } public void setHours () //This is a stub. { hours [0] [0] = 8; hours [0] [1] = 0; hours [0] [2] = 9; hours [1] [0] = 8; hours [1] [1] = 0; hours [1] [2] = 9; hours [2] [0] = 8; hours [2] [1] = 8; hours [2] [2] = 8; hours [3] [0] = 8; hours [3] [1] = 8; hours [3] [2] = 4; hours [4] [0] = 8; hours [4] [1] = 8; hours [4] [2] = 8; } public void update () { computeWeekHours (); computeDayHours (); } private void computeWeekHours () { for (employeeNumber = 1 ; employeeNumber <= numberOfEmployees ; employeeNumber++) { //Process one employee: int sum = 0; for (int day = MON ; day <= FRI ; day++) sum = sum + hours [day] [employeeNumber - 1]; //sum contains the sum of all the hours worked in //one week by the employee with number employeeNumber. weekHours [employeeNumber - 1] = sum; } } private void computeDayHours () { for (int day = MON ; day <= FRI ; day++) { //Process one day (for all employees): int sum = 0; for (int employeeNumber = 1 ; employeeNumber <= numberOfEmployees ; employeeNumber++) sum = sum + hours [day] [employeeNumber - 1]; //sum contains the sum of all hours worked by all //employees on one day. dayHours [day] = sum; } } public void showTable () { // heading System.out.print ("Employee "); for (int employeeNumber = 1 ; employeeNumber <= numberOfEmployees ; employeeNumber++) System.out.print (employeeNumber + " "); System.out.println ("Totals"); System.out.println (); // row entries for (int day = MON ; day <= FRI ; day++) { System.out.print (getDayName (day) + " "); for (int column = 0 ; column < hours [day].length ; column++) System.out.print (hours [day] [column] + " "); System.out.println (dayHours [day]); } System.out.println (); System.out.print ("Total = "); for (int column = 0 ; column < numberOfEmployees ; column++) System.out.print (weekHours [column] + " "); System.out.println (); } //Converts 0 to "Monday", 1 to "Tuesday", etc. //Blanks are inserted to make all strings the same length. private String getDayName (int day) { String dayName = null; switch (day) { case MON: dayName = "Monday "; break; case TUE: dayName = "Tuesday "; break; case WED: dayName = "Wednesday"; break; case THU: dayName = "Thursday "; break; case FRI: dayName = "Friday "; break; default: System.out.println ("Fatal Error."); System.exit (0); break; } return dayName; } } |
Listing 7.15 |
import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JTextArea; import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Oracle extends JApplet implements ActionListener { public static int LINES = 5; public static int CHAR_PER_LINE = 40; private JTextArea theText; private String question; private String answer; private String advice; public void init () { Container contentPane = getContentPane (); contentPane.setLayout (new FlowLayout ()); JLabel instructions = new JLabel ("I will answer any question, " + "but may need some advice from you."); contentPane.add (instructions); JButton getAnswerButton = new JButton ("Get Answer"); getAnswerButton.addActionListener (this); contentPane.add (getAnswerButton); JButton sendAdviceButton = new JButton ("Send Advice"); sendAdviceButton.addActionListener (this); contentPane.add (sendAdviceButton); JButton resetButton = new JButton ("Reset"); resetButton.addActionListener (this); contentPane.add (resetButton); theText = new JTextArea (LINES, CHAR_PER_LINE); theText.setText ("Questions and advice go here."); contentPane.add (theText); answer = "The answer is: Look around."; //first answer } public void actionPerformed (ActionEvent e) { String actionCommand = e.getActionCommand (); if (actionCommand.equals ("Get Answer")) { question = theText.getText (); theText.setText ("That is a difficult question.\n" + "Please give me some advice\n" + "and click the Send Advice button."); } else if (actionCommand.equals ("Send Advice")) { advice = theText.getText (); theText.setText ("That advice helped.\n" + "You asked the question: " + question + "\n" + answer + "\nClick the Reset button and" + "\nleave the program on for others."); answer = "The answer is: " + advice; } else if (actionCommand.equals ("Reset")) { theText.setText ("Questions and advice go here."); } else theText.setText ("Error"); } } |
Listing 7.16 |
import javax.swing.JApplet; import java.awt.Color; import java.awt.Graphics; public class House extends JApplet { private int [] xHouse = {150, 150, 200, 250, 250}; private int [] yHouse = {100, 40, 20, 40, 100}; private int [] xDoor = {175, 175, 200, 200}; private int [] yDoor = {100, 60, 60, 100}; private int [] xWindow = {220, 220, 240, 240}; private int [] yWindow = {60, 80, 80, 60}; public void paint (Graphics canvas) { super.paint(); this.setBackground (Color.LIGHT_GRAY); canvas.setColor (Color.GREEN); canvas.fillPolygon (xHouse, yHouse, xHouse.length); canvas.setColor (Color.BLACK); canvas.drawPolyline (xDoor, yDoor, xDoor.length); canvas.drawPolygon (xWindow, yWindow, xWindow.length); canvas.drawString ("Home sweet home!", 150, 120); } } |
Listing 8.1 |
public class Person { private String name; public Person () { name = "No name yet"; } public Person (String initialName) { name = initialName; } public void setName (String newName) { name = newName; } public String getName () { return name; } public void writeOutput () { System.out.println ("Name: " + name); } public boolean hasSameName (Person otherPerson) { return this.name.equalsIgnoreCase (otherPerson.name); } } |
Listing 8.2 |
public class Student extends Person { private int studentNumber; public Student () { super (); studentNumber = 0; //Indicating no number yet } public Student (String initialName, int initialStudentNumber) { super (initialName); studentNumber = initialStudentNumber; } public void reset (String newName, int newStudentNumber) { setName (newName); studentNumber = newStudentNumber; } public int getStudentNumber () { return studentNumber; } public void setStudentNumber (int newStudentNumber) { studentNumber = newStudentNumber; } public void writeOutput () { System.out.println ("Name: " + getName ()); System.out.println ("Student Number: " + studentNumber); } public boolean equals (Student otherStudent) { return this.hasSameName (otherStudent) && (this.studentNumber == otherStudent.studentNumber); } } |
Listing 8.3 |
public class InheritanceDemo { public static void main (String [] args) { Student s = new Student (); s.setName ("Warren Peace"); s.setStudentNumber (1234); s.writeOutput (); } } |
Listing 8.4 |
public class Undergraduate extends Student { private int level; //1 for freshman, 2 for sophomore, //3 for junior, or 4 for senior. public Undergraduate () { super (); level = 1; } public Undergraduate (String initialName, int initialStudentNumber, int initialLevel) { super (initialName, initialStudentNumber); setLevel (initialLevel); //Checks 1 <= initialLevel <= 4 } public void reset (String newName, int newStudentNumber, int newLevel) { reset (newName, newStudentNumber); //Students reset setLevel (newLevel); //Checks 1 <= newLevel <= 4 } public int getLevel () { return level; } public void setLevel (int newLevel) { if ((1 <= newLevel) && (newLevel <= 4)) level = newLevel; else { System.out.println ("Illegal level!"); System.exit (0); } } public void writeOutput () { super.writeOutput (); System.out.println ("Student Level: " + level); } public boolean equals (Undergraduate otherUndergraduate) { return equals ((Student) otherUndergraduate) && (this.level == otherUndergraduate.level); } } |
Listing 8.5 |
public boolean equals (Object otherObject)
{
boolean isEqual = false;
if ((otherObject != null) &&
(otherObject instanceof Student))
{
Student otherStudent = (Student) otherObject;
isEqual = this.sameName (otherStudent) &&
(this.studentNumber ==
otherStudent.studentNumber);
}
return isEqual;
}
|
Listing 8.6 |
public class PolymorphismDemo { public static void main(String[] args) { Person[] people = new Person[4]; people[0] = new Undergraduate("Cotty, Manny", 4910, 1); people[1] = new Undergraduate("Kick, Anita", 9931, 2); people[2] = new Student("DeBanque, Robin", 8812); people[3] = new Undergraduate("Bugg, June", 9901, 4); for (Person p : people) { p.writeOutput(); System.out.println(); } } } |
Listing 8.7 |
/** An interface for methods that return the perimeter and area of an object. */ public interface Measurable { /** Returns the perimeter. */ public double getPerimeter (); /** Returns the area. */ public double getArea (); } |
Listing 8.8 |
/** A class of rectangles. */ public class Rectangle implements Measurable { private double myWidth; private double myHeight; public Rectangle (double width, double height) { myWidth = width; myHeight = height; } public double getPerimeter () { return 2 * (myWidth + myHeight); } public double getArea () { return myWidth * myHeight; } } |
Listing 8.9 |
/** A class of circles. */ public class Circle implements Measurable { private double myRadius; public Circle (double radius) { myRadius = radius; } public double getPerimeter () { return 2 * Math.PI * myRadius; } public double getCircumference () { return getPerimeter (); } public double getArea () { return Math.PI * myRadius * myRadius; } } |
Listing 8.10 |
/** Interface for simple shapes drawn on the screen using keyboard characters. */ public interface ShapeInterface { /** Sets the offset for the shape. */ public void setOffset (int newOffset); /** Returns the offset for the shape. */ public int getOffset (); /** Draws the shape at lineNumber lines down from the current line. */ public void drawAt (int lineNumber); /** Draws the shape at the current line. */ public void drawHere (); } |
Listing 8.11 |
/** Interface for a rectangle to be drawn on the screen. */ public interface RectangleInterface extends ShapeInterface { /** Sets the rectangle's dimensions. */ public void set (int newHeight, int newWidth); } /** Interface for a triangle to be drawn on the screen. */ public interface TriangleInterface extends ShapeInterface { /** Sets the triangle's base. */ public void set (int newBase); } |
Listing 8.12 |
/** Class for drawing simple shapes on the screen using keyboard characters. This class will draw an asterisk on the screen as a test. It is not intended to create a "real" shape, but rather to be used as a base class for other classes of shapes. */ public class ShapeBasics implements ShapeInterface { private int offset; public ShapeBasics () { offset = 0; } public ShapeBasics (int theOffset) { offset = theOffset; } public void setOffset (int newOffset) { offset = newOffset; } public int getOffset () { return offset; } public void drawAt (int lineNumber) { for (int count = 0 ; count < lineNumber ; count++) System.out.println (); drawHere (); } public void drawHere () { for (int count = 0 ; count < offset ; count++) System.out.print (' '); System.out.println ('*'); } } |
Listing 8.13 |
/** Class for drawing rectangles on the screen using keyboard characters. Each character is higher than it is wide, so these rectangles will look taller than you might expect. Inherits getOffset, setOffset, and drawAt from the class ShapeBasics. */ public class Rectangle extends ShapeBasics implements RectangleInterface { private int height; private int width; public Rectangle () { super (); height = 0; width = 0; } public Rectangle (int theOffset, int theHeight, int theWidth) { super (theOffset); height = theHeight; width = theWidth; } public void set (int newHeight, int newWidth) { height = newHeight; width = newWidth; } public void drawHere () { drawHorizontalLine (); drawSides (); drawHorizontalLine (); } private void drawHorizontalLine () { skipSpaces (getOffset ()); for (int count = 0 ; count < width ; count++) System.out.print ('-'); System.out.println (); } private void drawSides () { for (int count = 0 ; count < (height - 2) ; count++) drawOneLineOfSides (); } private void drawOneLineOfSides () { skipSpaces (getOffset ()); System.out.print ('|'); skipSpaces (width - 2); System.out.println ('|'); } //Writes the indicated number of spaces. private static void skipSpaces (int number) { for (int count = 0 ; count < number ; count++) System.out.print (' '); } } |
Listing 8.14 |
/** Class for drawing triangles on the screen using keyboard characters. A triangle points up. Its size is determined by the length of its base, which must be an odd integer. Inherits getOffset, setOffset, and drawAt from the class ShapeBasics. */ public class Triangle extends ShapeBasics implements TriangleInterface { private int base; public Triangle () { super (); base = 0; } public Triangle (int theOffset, int theBase) { super (theOffset); base = theBase; } /** Precondition: newBase is odd. */ public void set (int newBase) { base = newBase; } public void drawHere () { drawTop (); drawBase (); } private void drawBase () { skipSpaces (getOffset ()); for (int count = 0 ; count < base ; count++) System.out.print ('*'); System.out.println (); } { //startOfLine == number of spaces to the //first '*' on a line. Initially set to the //number of spaces before the topmost '*'. int startOfLine = getOffset () + base / 2; skipSpaces (startOfLine); System.out.println ('*'); //top '*' int lineCount = base / 2 - 1; //height above base //insideWidth == number of spaces between the //two '*'s on a line. int insideWidth = 1; for (int count = 0 ; count < lineCount ; count++) { //Down one line, so the first '*' is one more //space to the left. startOfLine--; skipSpaces (startOfLine); System.out.print ('*'); skipSpaces (insideWidth); System.out.println ('*'); //Down one line, so the inside is 2 spaces wider. insideWidth = insideWidth + 2; } } private static void skipSpaces (int number) { for (int count = 0 ; count < number ; count++) System.out.print (' '); } } |
Listing 8.15 |
/** A program that draws a fir tree composed of a triangle and a rectangle, both drawn using keyboard characters. */ public class TreeDemo { public static final int INDENT = 5; public static final int TREE_TOP_WIDTH = 21; // must be odd public static final int TREE_BOTTOM_WIDTH = 4; public static final int TREE_BOTTOM_HEIGHT = 4; public static void main (String [] args) { drawTree (TREE_TOP_WIDTH, TREE_BOTTOM_WIDTH, TREE_BOTTOM_HEIGHT); } public static void drawTree (int topWidth, int bottomWidth, int bottomHeight) { System.out.println (" Save the Redwoods!"); TriangleInterface treeTop = new Triangle (INDENT, topWidth); drawTop (treeTop); RectangleInterface treeTrunk = new Rectangle (INDENT + (topWidth / 2) - (bottomWidth / 2), bottomHeight, bottomWidth); drawTrunk (treeTrunk); } private static void drawTop (TriangleInterface treeTop) { treeTop.drawAt (1); } private static void drawTrunk (RectangleInterface treeTrunk) { treeTrunk.drawHere (); // or treeTrunk.drawAt(0); } } |
Listing 8.16 |
public class Fruit { private String fruitName; public Fruit() { fruitName = ""; } public Fruit(String name) { fruitName = name; } public void setName(String name) { fruitName = name; } public String getName() { return fruitName; } } |
Listing 8.17 |
import java.util.Arrays; public class FruitDemo { public static void main(String[] args) { Fruit[] fruits = new Fruit[4]; fruits[0] = new Fruit("Orange"); fruits[1] = new Fruit("Apple"); fruits[2] = new Fruit("Kiwi"); fruits[3] = new Fruit("Durian"); Arrays.sort(fruits); // Output the sorted array of fruits for (Fruit f : fruits) { System.out.println(f.getName()); } } } |
Listing 8.18 |
public class Fruit implements Comparable { private String fruitName; public Fruit() { fruitName = ""; } public Fruit(String name) { fruitName = name; } public void setName(String name) { fruitName = name; } public String getName() { return fruitName; } public int compareTo(Object o) { if ((o != null) && (o instanceof Fruit)) { Fruit otherFruit = (Fruit) o; return (fruitName.compareTo(otherFruit.fruitName)); /*** Alternate definition of comparison using fruit length ***/ /* if (fruitName.length() > otherFruit.fruitName.length()) return 1; else if (fruitName.length() < otherFruit.fruitName.length()) return -1; else return 0; */ } return -1; // Default if other object is not a Fruit } } |
Listing 8.19 |
/** Abstract base class for drawing simple shapes on the screen using characters. */ public abstract class ShapeBase implements ShapeInterface { private int offset; public abstract void drawHere (); /* The rest of the class is identical to ShapeBasics in Listing 8.11, except for the names of the constructors.Only the method drawHere is abstract. Methods other than drawHere have bodies and do not have the keyword abstract in heir headings. We repeat one such method here: */ public void drawAt (int lineNumber) { for (int count = 0 ; count < lineNumber ; count++) System.out.println (); drawHere (); } } |
Listing 8.20 |
import javax.swing.JButton; import javax.swing.JFrame; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** Simple demonstration of putting buttons in a JFrame window. */ public class ButtonDemo extends JFrame implements ActionListener { public static final int WIDTH = 400; public static final int HEIGHT = 300; public ButtonDemo () { setSize (WIDTH, HEIGHT); WindowDestroyer listener = new WindowDestroyer (); addWindowListener (listener); Container contentPane = getContentPane (); contentPane.setBackground (Color.WHITE); contentPane.setLayout (new FlowLayout ()); JButton sunnyButton = new JButton ("Sunny"); sunnyButton.addActionListener (this); contentPane.add (sunnyButton); JButton cloudyButton = new JButton ("Cloudy"); cloudyButton.addActionListener (this); contentPane.add (cloudyButton); } public void actionPerformed (ActionEvent e) { String actionCommand = e.getActionCommand (); Container contentPane = getContentPane (); if (actionCommand.equals ("Sunny")) contentPane.setBackground (Color.BLUE); else if (actionCommand.equals ("Cloudy")) contentPane.setBackground (Color.GRAY); else System.out.println ("Error in button interface."); } } |
Listing 8.21 |
public class ShowButtonDemo { public static void main (String [] args) { ButtonDemo gui = new ButtonDemo (); gui.setVisible (true); } } |
Listing 8.22 |
import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; /** If you register an object of this class as a listener to any object of the class JFrame, the object will end the program and close the JFrame window if the user clicks the window's close-window button. */ public class WindowDestroyer extends WindowAdapter { public void windowClosing (WindowEvent e) { System.exit (0); } } |