Revised Exchange Rate Calculator
So far only for Norwegian Kroner
On request from one of the Remember Java readers, I've updated the old
Exchange Rate Calculator to work with the new tables on the
exchange rate page
of the Norwegian newspaper Aftenposten. This example will thus only
convert to or from the Norwegian currency NOK. For a universal calculator,
please see next week's article, which uses Google's excellent exchange
information search functionality.
|
The code in this revised edition is surprisingly similar to the old version.
In fact, there were only minor changes needed, and for the most important bit
of the parsing code, all that was necessary was to delete several lines of code and
replace them with two new ones taking advantage of the grep functionality
introduced in Java 1.4.
The parsing code is making the assumption that the bits of information we're
interested, currency name and price, are present on separate lines. Furthermore,
it is assumed that the currency abbreviation is in upper case and that the price is
using the digits 0-9, which seems safe enough. The final assumption is that no
other information on the line is of this kind (upper case letters or numbers).
An example of these lines from the exchange rate page is shown below:
</td><td>USD</td>
<td class="colright">6,1633</td>
Please note that the decimal marker in Norwegian is a comma, rather than
a the English notation, a dot.
|
|
To extract only upper case characters or numbers (and the comma) from these strings,
the following code will do, given that the String variable line contains
the data:
String numbers = line.replaceAll("[^0-9,]", "");
String uppercase = line.replaceAll("[^A-Z]", "");
In the second line, a regular expression is used to replace all characters which are not
upper case letter with an empty string. Note that the hat (^), is the negation
character of grep. In the first line, this is used to remove all characters which
are not digits or a comma.
And that's all it takes. Pretty much the rest of the code stays the same (some
cleanup would maybe have been appropriate, but that will have to wait). The URL
is updated and hard coded at the end of the class to point to the new
Aftenposten exchange rate site.
NOKExchangeRateCalculator.java
|
|
|