720 likes | 832 Vues
In this chapter, we explore how to utilize arrays and vectors in Java for managing price data effectively. Learn to print all price values, identify the lowest price among them, and handle variable amounts of data. This guide covers array initialization, accessing elements with index operators, common errors in bounds, copying arrays, and managing partially filled arrays. Additionally, discover techniques for growing dynamic arrays and using methods to compute averages and search for values, along with code examples for practical implementation.
E N D
Chapter 11 Arrays and Vectors
Print all prices, mark the lowest • 19.9523.9524.9518.95 <- lowest price29.9519.9520.0022.9924.9519.95
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];
Figure 1 An Array Reference and an Array
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
Figure 2 Filling an Array Element
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;
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++)
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
Figure 3 Copying an Array Reference
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);
Figure 4 The System.arrayCopy Method
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++;
Figure 5 Size of a Partially Filled Array
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;
Figure 6 Growing a Dynamic Array
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;
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
for (int i = 0; i < dataSize; i++) { System.out.print(data[i]); if (data[i] == lowest) System.out.print(” <--lowest price"); System.out.println(); } } }
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);
Figure 7 Passing an Array to a Method
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);
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]);
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");
Figure 8 Removing an Element from an Array
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();
// 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]); } }
Figure 9 Removing an Element from an Ordered Array Element
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
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]); } }
Figure 10 Inserting an Element in an Ordered Array
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();
// 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); }
/** 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]); } }
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;
Figure 11 Parallel Arrays
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);
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++; }
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;
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]);
// mark if best buy if (scores[i] / prices[i] == best) System.out.print(” <-- best buy"); System.out.println(); } } }
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
Figure 12 Eliminating Parallel Arrays
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;
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();
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(); } }
/** 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); }
/** 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()); } }
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
Figure 13 A Polygon