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()); } }