©2000, john wiley & sons, inc. horstmann/java essentials, 2/e chapter 11: arrays and vectors 1...

72
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

Upload: ethel-nichols

Post on 20-Jan-2016

217 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors1

Chapter 11

Arrays and Vectors

Page 2: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors2

Print all prices, mark the lowest

• 19.9523.9524.9518.95 <- lowest price29.9519.9520.0022.9924.9519.95

Page 3: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors3

Variable number of values

• Can't just have variables data1, data2, ..., data10

• Code would be tedious• What if we have 1000 numbers?• Array = collection of values of the same type• double[] data = new double[10];

Page 4: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors4

Figure 1An Array Reference and anArray

Page 5: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors5

Accessing array elements

• Index (or subscript) operator data[4] = 29.95;System.out.println(data[4]);

• Unpleasant detail: data[4] is the fifth value in the array

• data[0] = the first valuedata[1] = the second value. . .data[9] = the tenth value

Page 6: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors6

Figure 2Filling an ArrayElement

Page 7: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors7

Common Errors

• Bounds errorint i = 20;System.out.println(data[i]);

• Most common form: double[] data=new double[20];data[20] = 19.95;

• Forgot to initialize:double[] data;data[0] = 19.95;

Page 8: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors8

Array length

• Public instance variable length yields number of elements in array, e.g. a.length

• Read-only. Can't assign to a.length• Most common use: for (int i = 0; i < a.length; i++) do something with a[i]

• Asymmetric bounds: 0 £ i < a.lengthDon't use for (int i = 0; i <= a.length - 1; i++)

Page 9: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors9

Copying Arrays

• Array variables are references:double[] data=new double[10];double[] prices = data;Now both variables point to the same array

• data[0] = 19.95;Now both data[0] and prices[0] are 19.95

Page 10: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors10

Figure 3Copying an ArrayReference

Page 11: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors11

Copying all values of an array

• Explicit loop:double[] prices = new double[data.length];for (int i = 0; i < data.length; i++) prices[i] = data[i];

• Use System.arraycopySystem.arraycopy(data, 0, prices, 0, data.length);

Page 12: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors12

Figure 4The System.arrayCopy Method

Page 13: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors13

Partially Filled Arrays

• Problem: Don't know how many data values are in the input set

• Remedy: Make the array larger than the largest data set, remember how much is filled

• final int DATA_LENGTH = 1000;double[] data = new double[DATA_LENGTH];int dataSize = 0;

• Fill in values and increment size data[dataSize] = new value;dataSize++;

Page 14: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors14

Figure 5Size of a Partially Filled Array

Page 15: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors15

Partially Filled Arrays

• Use the _LENGTH, Size naming convention!• What if the array fills up? Can refuse additional

entries:if (dataSize >= DATA_LENGTH) System.out.println("Sorry");

• Can grow array:double[] newData=new double[2*data.length];System.arrayCopy(data,0,newData,0, data.length);data = newData;

Page 16: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors16

Figure 6Growing a Dynamic Array

Page 17: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors17

Program BestPrice.java

public class BestPrice{ public static void main(String[] args) { final int DATA_LENGTH = 1000; double[] data = new double[DATA_LENGTH]; int dataSize = 0;

// read data

ConsoleReader console = new ConsoleReader(System.in);

boolean done = false; while (!done) { System.out.println("Enter price, 0 to quit:"); double price = console.readDouble(); if (price ++ 0) // end of input done = true;

Page 18: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors18

else if (dataSize < data.length) { // add price to data array data[dataSize] = price; dataSize++; } else // array is full { System.out.println("Sorry, the array is full."); done = true; }}

// compute lowest price

if (dataSize == 0) return; // no datadouble lowest = data[0];for (int i = 1; i < dataSize; i++) if (data[i] < lowest) lowest = data[i];// print out prices, marking the lowest one

Page 19: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors19

for (int i = 0; i < dataSize; i++) { System.out.print(data[i]); if (data[i] == lowest) System.out.print(” <--lowest price"); System.out.println(); } }}

Page 20: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors20

Array Parameters

• static double average(double[] data){ if (data.length == 0) return 0; double sum = 0; for (int i = 0; i < data.length; i++) sum = sum + data[i]; return sum / n;}

• Call asdouble[] prices = new double[20];. . .double avg = average(prices);

Page 21: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors21

Figure 7Passing an Array to a Method

Page 22: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors22

Returning an Array

• Construct an array with random test datastatic int[] randomData(int length, int n){ Random generator = new Random(); int[] data = new int[length]; for (int i = 0; i < data.length; i++) data[i] = generator.nextInt(n); return data;}

• Call asint[] data = randomData(length, n);

Page 23: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors23

Common algorithms: find value• double[] prices = . . .;double targetPrice = 1000;int i = 0;boolean found = false;while (i < prices.length && !found){ if (prices [i] <= targetPrice) found = true; else i++;}if (found) System.out.println("Item " + i + " has a price of " + prices[i]);

Page 24: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors24

Common algorithms: count values

• double[] prices = . . .;double targetPrice = 1000;int count = 0;for(i = 0; i < prices.length; i++){ if (prices [i] <= targetPrice) count++;}System.out.println(count + " matches");

Page 25: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors25

Figure 8Removing an Elementfrom an Array

Page 26: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors26

Program Remove1.java

public class Remove1{ public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); String[] staff = new String[5];

staff[0] = "Harry";staff[1] = "Romeo";staff[2] = "Dick";staff[3] = "Juliet";staff[4] = "Tom";int staffSize = staff.length;

print(staff, staffSize);

System.out.println("Remove which element? (0 - 4)");int pos = console.readInt();

Page 27: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors27

// overwrite the removed element with the last element

staff[pos] = staff[staffSize - 1]; staffSize--;

print(staff,staffSize); }

/** Prints an array of strings @param s the string array @param sSize the number of strings in the array */ public static void print(String[] s, int sSize) { for (int i = 0; i < sSize; i++) System.out.println(i + ": ” + s[i]); }}

Page 28: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors28

Figure 9Removing an Elementfrom anOrdered ArrayElement

Page 29: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors29

Program Remove2.java

public class Remove2{ public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in);

String[] staff = new String[5];staff[0] = "Dick";staff[1] = "Harry";staff[2] = "Juliet";staff[3] = "Romeo";staff[4] = "Tom";int staffSize = staff.length;

print(staff, staffSize);

System.out.println("Remove which element? (0 - 4)");int pos =console.readInt();

// shift all elements above pos down

Page 30: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors30

for (int i = pos; i < staffSize - 1; i++) staff[i] = staff[i + 1];

staffSize--;

print(staff, staffSize); }

/** Prints an array of strings @param s the string array @param sSize the number of strings in the array */ public static void print(String[] s, int sSize) { for (int i = 0; i < sSize; i++) System.out.println(i + ": ” + s[i]); }}

Page 31: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors31

Figure 10Inserting an Element inan Ordered Array

Page 32: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors32

Program Insert.java

public class Insert{ public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); String[] staff = new String[6]; staff[0] = "Dick"; staff[1] = "Harry"; staff[2] = "Juliet"; staff[3] = "Romeo"; staff[4] = "Tom"; int staffSize = staff.length - 1;

print(staff, staffSize);

System.out.print ("Insert before which element? (0 - 4)"); int pos = console.readInt();

Page 33: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors33

// shift all element after pos up by one

for (int i = staffSize; i > pos; i--) staff[i] = staff[i - 1];

// insert new element into freed slot

staff[pos] = "New, Nina";

staffSize++;

print(staff, staffSize);}

Page 34: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors34

/** Prints an array of strings @param s the string array @param sSize the number of strings in the array */ public static void print(String[] s, int sSize) { for (int i = 0; i < sSize; i++) System.out.println(i + ": ” + s[i]); }}

Page 35: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors35

Parallel Arrays

• Product dataAceAcro 740 $3499.0 score = 71ACMA P500 $3195.0 score = 64Maximus $2495.0 score = 72<-best buySummit $2995.0 score = 48

• Naive solution: 3 “parallel” arraysString[] names;double[] prices;int[] scores;

Page 36: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors36

Figure 11Parallel Arrays

Page 37: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors37

Program BestData.java

public class BestData{ public static void main(String[] args) { final int DATA_LENGTH = 1000; String[] names = new String[DATA_LENGTH]; double[] prices = new double[DATA_LENGTH]; int[] scores = new int[DATA_LENGTH];

int dataSize = 0;

// read data ConsoleReader console = new ConsoleReader(System.in);

Page 38: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors38

boolean done = false;while (!done){ System.out.println ("Enter name or leave blank when done:"); String inputLine = console.readLine(); if (inputLine == null || inputLine.equals("")) done = true; else if (dataSize < DATA_LENGTH)

{ names[dataSize] = inputLine; System.out.println("Enter price:"); inputLine = console.readLine(); prices[dataSize] = Double.parseDouble(inputLine); System.out.println("Enter score:"); inputLine = console.readLine(); scores[dataSize] = Integer.parseInt(inputLine); dataSize++; }

Page 39: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors39

else // array is full { System.out.println("Sorry, the array is full."); done = true; }}

// compute best buy

if (dataSize == 0) return; // no datadouble best = scores[0] / prices[0];for (int i = 1; i < dataSize; i++) if (scores[i] / prices[i] > best) best = scores[i] / prices[i];

// print out products, marking the best buys

final int COLUMN_WIDTH = 30;

Page 40: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors40

for (int i = 0; i < dataSize; i++){ System.out.print(names[i]);

// pad with spaces to fill column

int pad = COLUMN_WIDTH - names[i].length(); for (int j = 1; j <= pad; j++) System.out.print(” ");

// print price and score

System.out.print(” $” + prices[i] + ” score = ” + scores[i]);

Page 41: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors41

// mark if best buy

if (scores[i] / prices[i] == best) System.out.print(” <-- best buy"); System.out.println(); } }}

Page 42: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors42

Eliminating parallel arrays

• Parallel arrays are an indication of a missed opportunity for finding objects

• class Product{ . . . private String name; private double price; private int score;}

• Product[] products

Page 43: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors43

Figure 12Eliminating Parallel Arrays

Page 44: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors44

Program BestProduct.java

public class BestProduct{ public static void main(String[] args) { final int DATA_LENGTH = 1000; Product[] data = new Product[DATA_LENGTH]; int dataSize = 0;

// read data

ConsoleReader console = new ConsoleReader(System.in);

boolean done = false; while (!done) { Product p = readProduct(console); if (p == null) done = true;

Page 45: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors45

else if (dataSize < DATA_LENGTH) { data[dataSize] = p; dataSize++; } else // array is full { System.out.println("Sorry, the array is full."); done = true; }}

// compute best buy

if (dataSize == 0) return; // no data

double best = data[0].getScore() / data[0].getPrice();

Page 46: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors46

for (int i = 1; i < dataSize; i++) { double ratio = data[i].getScore() / data[i].getPrice(); if (ratio > best) best = ratio; }

// print out data, marking the best buys

for (int i = 0; i < dataSize; i++) { printProduct(data[i]); if (data[i].getScore() / data[i].getPrice() == best) System.out.print(” <-- best buy"); System.out.println(); }}

Page 47: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors47

/** Reads a product from a console reader. @param in the reader @return the product read if a product was successfully read, null if end of input was detected*/

public static Product readProduct(ConsoleReader in){ System.out.println ("Enter name or leave blank when done:"); String name = in.readLine(); if (name == null || name.equals("")) return null; System.out.println("Enter price:"); String inputLine = in.readLine(); double price = Double.parseDouble(inputLine); System.out.println("Enter score:"); inputLine = in.readLine(); int score = Integer.parseInt(inputLine); return new Product(name, price, score);}

Page 48: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors48

/** Prints a product description. @param p the product to print */ public static void printProduct(Product p) { final int COLUMN_WIDTH = 30;

System.out.print(p.getName());

// pad with spaces to fill column

int pad = COLUMN_WIDTH - p.getName().length(); for (int i = 1; i <= pad; i++) System.out.print(” ");

System.out.print(” $” + p.getPrice() + ” score = ” + p.getScore()); }}

Page 49: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors49

Arrays of Objects• public class Polygon{ public Polygon(int n) { corners = new Point2D.Double[n]; cornersSize = 0; } public void add(int i,Point2D.Double p) { if (cornersSize < corners.length) { corners[cornersSize] = p; cornersSize++; } } public void draw(Graphics2D g2) {...} private Point2D.Double[] corners;}

• x

Page 50: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors50

Figure 13A Polygon

Page 51: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors51

Arrays of objects

• corners=new Point2D.Double[n]creates an array of null references

• Need to set each of them to an object:corners[cornersSize] = p;

• Polygon example:Polygon triangle = new Polygon(3);triangle.add(new Point2D.Double(40,40));triangle.add(new Point2D.Double(120,160));triangle.add(new Point2D.Double(20,120));

Page 52: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors52

Arrays of objects

• draw method:public void draw(Graphics2D g2){ for (int i = 0; i < cornersSize; i++) { Point2D.Double from = corners[i]; Point2D.Double to = corners[(i + 1) % cornersSize]; g2.draw(new Line2D.Double(from, to));}

• Why not juststatic void drawPolygon(Graphics2D g2, Point2D.Double[] a)

Page 53: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors53

Figure 14The Output of thePolygonTest program

Page 54: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors54

Program PolygonTest.java

import java.applet.Applet;import java.awt.Graphics; import java.awt.Graphics2D;import java.awt.geom.Line2D;import java.awt.geom.Point2D;

public class PolygonTest extends Applet{ public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g;

Polygon triangle = new Polygon(3); triangle.add(new Point2D.Double(40, 40)); triangle.add(new Point2D.Double(120, 160)); triangle.add(new Point2D.Double(20, 120));

Page 55: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors55

double x = 200; double y = 200; double r = 50; Polygon pentagon = new Polygon(5); for (int i = 0; i < 5; i++) pentagon.add(new Point2D.Double( x + r * Math.cos(2 * Math.PI * i / 5), y + r * Math.sin(2 * Math.PI * I / 5)));

triangle.draw(g2); pentagon.draw(g2); }}

/** A polygon is a closed curve made up from line segment that join the corner points.*/

Page 56: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors56

class Polygon{ /** Constructs a polygon with a given number of corner points. @param n the number of corner points. */ public Polygon(int n) { corners = new Point2D.Double[n]; cornersSize = 0; }

/** Adds a corner point of the polygon. The point is ignored if the maximum number of points has been added. @param p the corner point */ public void add(Point2D.Double p) { if (cornersSize < corners.length)

Page 57: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors57

{ corners[cornersSize] = p; cornersSize++; }}

/** Draws the polygon. @param g2 the graphics context*/public void draw(Graphics2D g2){ for (int i = 0; i < cornersSize; i++) { Point2D.Double from = corners[i]; Point2D.Double to = corners[(i + 1) % corners.length]; g2.draw(new Line2D.Double(from, to)); }}

Page 58: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors58

private Point2D.Double[] corners; private int cornersSize;}

Page 59: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors59

Program CloudTest.java

import java.applet.Applet;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.geom.Ellipse2D;import java.awt.geom.Point2D;import java.util.Random;

public class CloudTest extends Applet{ public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g;

Random generator = new Random();

final int CLOUD_SIZE = 100; Cloud randomCloud = new Cloud(CLOUD_SIZE);

for (int i = 0; i < CLOUD_SIZE; i++) { // generate two random numbers between 100 and 200

Page 60: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors60

double x = 100 + 100 * generator.nextDouble(); double y = 100 + 100 * generator.nextDouble();

randomCloud.add(new Point2D.Double(x, y)); }

randomCloud.draw(g2); }}

/** A cloud is a collection of dots.*/

class Cloud{ /** Constructs a cloud with a given number of dots. @param n the number of dots. */

Page 61: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors61

public Cloud(int n){ dots = new Point2D.Double[n]; dotsSize = 0;}

/** Sets a dot point of the cloud. The point is ignored if the maximum number of points has been added. @param p the dot point*/public void add(Point2D.Double p){ if (dotsSize < dots.length) { dots[dotsSize] = p; dotsSize++; }}

/** Draws the cloud. @param g2 the graphics context*/

Page 62: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors62

public void draw(Graphics2D g2) { final double SMALL_CIRCLE_RADIUS = 2;

for (int i = 0; i < dotsSize; i++) { Ellipse2D.Double smallCircle = new Ellipse2D.Double( dots[i].getX() - SMALL_CIRCLE_RADIUS, dots[i].getY() - SMALL_CIRCLE_RADIUS, 2 * SMALL_CIRCLE_RADIUS, 2 * SMALL_CIRCLE_RADIUS);

g2.draw(smallCircle); } }

private Point2D.Double[] dots; private int dotsSize;}

Page 63: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors63

Figure 15The Output of theCloudTest Program

Page 64: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors64

Vectors

• Dynamically growing array of objectsVector products = new Vector();

• No need to set length. Can add as many elements as desiredProduct p = . . .;products.add(p);

• Overwrite existing elementproducts.set(i, p);

Page 65: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors65

Vectors

• Get current size:for (i=0; i<products.size(); i++)

• Must use cast to get elementsProduct p = (Product)products.get(i);

• Must wrap numbers into wrapper classesdata.add(new Double(3.14));x = ((Double)data.get(i)).doubleValue();

• Can copy into array (after growing stops)Product[] a = new Product[v.size()];v.copyInto(a);

Page 66: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors66

Program Table2.java

public class Table2{ public static void main(String[] args) { final int COLUMN_WIDTH = 10;

int[][] powers = new int[10][8]; for (int i = 0; i < powers.length; i++) for (int j = 0; j < powers[i].length; j++) powers[i][j] = (int)Math.pow(i + 1, j + 1);

printTable(powers, COLUMN_WIDTH);}

/** Prints a two-dimensional array of integers @param table the values to be printed @param width the column width*/

Page 67: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors67

2D Arrays

• Store table of powers xy

1 1 1 1 1 2 4 8 16 32 3 9 27 81 243 . . .

• int[][] powers = new int[rows][columns]

• powers[3][4] = Math.pow(3, 4);

Page 68: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors68

public static void printTable(int[][] table, int width){ for (int i = 0; i < table.length; i++) { for (int j = 0; j < table[i].length; j++) { System.out.print(format(table[i][j], width)); } System.out.println(); }}/** Formats an integer to fit in a field of constant width. @param n the integer to format @param width the field width @return a string of length width, consisting of leading spaces followed by the number n*/

Page 69: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors69

public static String format(int n, int width) { String nstr = "” + n;

// pad with spaces

while (nstr.length() < width) nstr = ” ” + nstr;

return nstr; }}

Page 70: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors70

Figure 16A Two-Dimensional Array

Page 71: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors71

Figure 17Glider

Page 72: ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

Chapter 11: Arrays and Vectors72

Figure 18Glider Gun