Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors."— Presentation transcript:

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

2 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 2 Print all prices, mark the lowest 19.95 23.95 24.95 18.95 <- lowest price 29.95 19.95 20.00 22.99 24.95 19.95

3 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 3 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];

4 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 4 Figure 1 An Array Reference and an Array

5 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 5 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 value data[1] = the second value... data[9] = the tenth value

6 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 6 Figure 2 Filling an Array Element

7 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 7 Common Errors Bounds error int 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;

8 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 8 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.length Don't use for (int i = 0; i <= a.length - 1; i++)

9 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 9 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

10 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 10 Figure 3 Copying an Array Reference

11 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 11 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.arraycopy System.arraycopy(data, 0, prices, 0, data.length);

12 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 12 Figure 4 The System.arrayCopy Method

13 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 13 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++;

14 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 14 Figure 5 Size of a Partially Filled Array

15 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 15 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;

16 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 16 Figure 6 Growing a Dynamic Array

17 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 17 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;

18 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 18 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 data double lowest = data[0]; for (int i = 1; i < dataSize; i++) if (data[i] < lowest) lowest = data[i]; // print out prices, marking the lowest one

19 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 19 for (int i = 0; i < dataSize; i++) { System.out.print(data[i]); if (data[i] == lowest) System.out.print(” <--lowest price"); System.out.println(); }

20 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 20 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 as double[] prices = new double[20];... double avg = average(prices);

21 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 21 Figure 7 Passing an Array to a Method

22 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 22 Returning an Array Construct an array with random test data static 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 as int[] data = randomData(length, n);

23 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 23 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]);

24 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 24 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");

25 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 25 Figure 8 Removing an Element from an Array

26 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 26 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();

27 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 27 // 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]); }

28 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 28 Figure 9 Removing an Element from an Ordered Array Element

29 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 29 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

30 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 30 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]); }

31 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 31 Figure 10 Inserting an Element in an Ordered Array

32 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 32 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();

33 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 33 // 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); }

34 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 34 /** 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]); }

35 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 35 Parallel Arrays Product data AceAcro 740 $3499.0 score = 71 ACMA P500 $3195.0 score = 64 Maximus $2495.0 score = 72<-best buy Summit $2995.0 score = 48 Naive solution: 3 “parallel” arrays String[] names; double[] prices; int[] scores;

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

37 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 37 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);

38 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 38 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++; }

39 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 39 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 = 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;

40 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 40 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]);

41 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 41 // mark if best buy if (scores[i] / prices[i] == best) System.out.print(” <-- best buy"); System.out.println(); }

42 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 42 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

43 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 43 Figure 12 Eliminating Parallel Arrays

44 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 44 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;

45 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 45 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();

46 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 46 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(); }

47 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 47 /** 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); }

48 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 48 /** 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()); }

49 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 49 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

50 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 50 Figure 13 A Polygon

51 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 51 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));

52 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 52 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 just static void drawPolygon(Graphics2D g2, Point2D.Double[] a)

53 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 53 Figure 14 The Output of the PolygonTest program

54 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 54 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));

55 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 55 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. */

56 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 56 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)

57 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 57 { 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)); }

58 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 58 private Point2D.Double[] corners; private int cornersSize; }

59 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 59 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

60 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 60 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. */

61 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 61 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 */

62 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 62 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; }

63 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 63 Figure 15 The Output of the CloudTest Program

64 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 64 Vectors Dynamically growing array of objects Vector products = new Vector(); No need to set length. Can add as many elements as desired Product p =...; products.add(p); Overwrite existing element products.set(i, p);

65 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 65 Vectors Get current size: for (i=0; i<products.size(); i++) Must use cast to get elements Product p = (Product)products.get(i); Must wrap numbers into wrapper classes data.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);

66 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 66 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 */

67 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 67 2D Arrays Store table of powers x y 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);

68 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 68 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 */

69 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 69 public static String format(int n, int width) { String nstr = "” + n; // pad with spaces while (nstr.length() < width) nstr = ” ” + nstr; return nstr; }

70 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 70 Figure 16 A Two-Dimensional Array

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

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


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

Similar presentations


Ads by Google