06.01.2013 Views

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

338 <strong>Learning</strong> <strong>Processing</strong><br />

String url = " http://xml.weather.yahoo.com/forecastrss?p = 10003 " ;<br />

String[] lines = loadStrings(url);<br />

// Get rid of the array in order <strong>to</strong> search<br />

// the whole page<br />

String xml = join(lines, " " );<br />

// Searching for temperature<br />

String tag1 = " temp = \ " " ;<br />

String tag2 = " \ " " ;<br />

temp = int(giveMeTextBetween<br />

(xml,tag1,tag2));<br />

println(temp);<br />

Example 18-5 retrieves the temperature from Yahoo’s weather XML feed and displays it onscreen. Th e<br />

example also uses object-oriented programming, putting all of the String parsing functionality in<strong>to</strong> a<br />

WeatherGrabber class.<br />

Example 18-5: Parsing Yahoo’s XML weather feed manually<br />

PFont f;<br />

String[] zips = { " 10003 ", " 21209 ", " 90210 " } ;<br />

int counter = 0;<br />

// The WeatherGrabber object does the work for us!<br />

WeatherGrabber wg;<br />

void setup() {<br />

size(200,200);<br />

// Make a WeatherGrabber object<br />

wg = new WeatherGrabber(zips[counter]);<br />

// Tell it <strong>to</strong> request the weather<br />

wg.requestWeather();<br />

f = createFont( " Georgia " ,16,true);<br />

}<br />

void draw() {<br />

background(255);<br />

textFont(f);<br />

fill(0);<br />

// Get the values <strong>to</strong> display<br />

String weather = wg.getWeather();<br />

int temp = wg.getTemp();<br />

// Display all the stuff we want <strong>to</strong> display<br />

text(zips[counter],10,160);<br />

text(weather,10,90);<br />

text(temp,10,40);<br />

text(" Click <strong>to</strong> change zip. " ,10,180);<br />

// Draw a little thermometer based on the temperature<br />

stroke(0);<br />

fill(175);<br />

rect(10,50,temp*2,20);<br />

}<br />

A quote in Java marks the beginning or end of a String. So how<br />

do we include an actual quote in a String?<br />

The answer is via an “escape” sequence. (We encountered this<br />

in Exercise 17-8.) A quote can be included in a String using a<br />

backward slash, followed by a quote. For example:<br />

String q = "This String has a quote \"in it";<br />

fi g. 18.9<br />

The WeatherGrabber object is initialized with<br />

a zip code. The XML data is loaded and parsed<br />

upon calling the requestWeather() function.<br />

The weather and temperature information is<br />

pulled from the WeatherGrabber object.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!