import java.io.PrintStream; import java.util.Scanner; import java.net.URL; import java.io.IOException; import javax.swing.JOptionPane; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; public class Prices { public static void main(String[] arguments) throws IOException { Scanner input = new Scanner(System.in); PrintStream output = System.out; URL url = new URL("http://store.apple.com/us/browse/home/shop_ipod/ipod_accessories/speakers?mco=MTM3NDk3OTE&s=priceHL"); Scanner webInput = new Scanner(url.openStream()); final String ITEM = "
"; final String PRICE = ".*>\\$\\d{1,4}\\.\\d{2}<.*"; // Offsets used to isolate specific parts of the item and price strings // These are highly dependent on the structure of the html document final int ITEM_OFFSET = 7; final int PRICE_OFFSET = 2; Map prices = new TreeMap(); String thisItem = null; while (webInput.hasNextLine()) { String line = webInput.nextLine().trim(); if (line.matches(ITEM)) { int start = line.indexOf("title") + ITEM_OFFSET; int end = line.indexOf("\"", start); thisItem = line.substring(start, end); } else if (line.matches(PRICE) && thisItem != null) { int start = line.indexOf('>') + PRICE_OFFSET; int end = line.indexOf('<', start); String thisPrice = line.substring(start, end); prices.put(thisItem, thisPrice); thisItem = null; } } for (String item : prices.keySet()) { output.printf("$%s %s%n", prices.get(item), item); } double THRESHOLD = 300; Iterator iter = prices.values().iterator(); while (iter.hasNext()) { double price = Double.parseDouble(iter.next()); if (price < THRESHOLD) { iter.remove(); } } output.println("---"); for (String item : prices.keySet()) { output.printf("$%s %s%n", prices.get(item), item); } } }