import java.util.Scanner; import java.io.PrintStream; import java.net.URL; import java.io.IOException; import javax.swing.JOptionPane; /** * Displays an information message with the current temperature in Toronto. * * @author Franck van Breugel */ public class Temperature { public static void main(String[] args) throws IOException { Scanner input = new Scanner(System.in); PrintStream output = System.out; // create a Scanner to read from the URL of the weather network URL url = new URL("http://www.theweathernetwork.com/weather/caon0696"); Scanner urlInput = new Scanner(url.openStream()); final String BEGIN = "

"; final String END = "

"; final String PATTERN = BEGIN + "-?\\d{1,2}" + END; // read the web page line by line while (urlInput.hasNextLine()) { String line = urlInput.nextLine().trim(); // if the line matches the pattern if (line.matches(PATTERN)) { // extract the temperature int temperature = Integer.parseInt(line.substring(BEGIN.length(), line.length() - END.length())); // display an information message with the temperature JOptionPane.showMessageDialog(null, "" + temperature + " C", "Current temperature in Toronto", JOptionPane.INFORMATION_MESSAGE); } } // close the Scanner urlInput.close(); } }