java 汇率换算_[java] 汇率换算器实现(2)

(19) 2024-04-08 22:01:01

首先让我们来观察一下需要处理的网页的source code.

货币名称
现汇买入价
现钞买入价
卖出价
中间价
基准价
美元 USD
621.8700 
616.8900 
624.3700 
623.1200 
615.5700 

分析发现, 汇率表由大写的TABLE包括起来, 每一行由TR包围, 每一项由TD包围. 因此, 正则表达式为:

\(.*?\): now "\1" means "美元 USD"\(.*?\)

对于上述字符的识别可以用以下方式进行实现:

str.startwith(token), where token = "

str.startwith("

str.startwith("

to extract the unit of the money

import java.util.regex.*;

String patt = "

\\(.*?\\)"

Pattern r = Pattern.compile(patt);

Matcher m = r.matcher(str);

m.group(1); // is the result, such as "美元 USD"

用类似的方法可以获得rates

然后编写代码进行实现, 具体实现思路如下:

实现html源代码中关于汇率表的相关内容行的识别

然后, 从特定的行中提取出相应的汇率信息

classRate {//从网站:http://www.usd-cny.com/中获取最新的汇率信息

final static String webSite = "http://www.usd-cny.com/";//利用hashtable对不同货币之间的利率进行存储//key: $from+$to, value: $rate

private static Hashtable rateTable = newHashtable();//从网上自动更新汇率信息//只将前16个具有完整汇率信息的内容进行存储

public static void update() throwsException {

URL hp= newURL(webSite);

URLConnection hpCon=hp.openConnection();

System.out.println("== Content ==");

InputStream input=(InputStream)hpCon.getInputStream();

BufferedReader br= new BufferedReader(newInputStreamReader(input,"gb2312"));

String str= null;boolean inTable = false;int nRows = 0;

String matchStr= null;while (( str = br.readLine() ) != null) {

str=str.trim();//判断是否进入汇率表的势力范围内部

if (str.startsWith("

inTable= true;continue;

}if (str.startsWith("

}if (inTable == false)continue;if (str.startsWith("

nRows+= 1;//忽略第一行的标题

if (nRows == 1) continue;//汇率表的读取只到港币

if (nRows == RateInfo.NKINDS+2) break;//获得第一列的完整代码

str =br.readLine().trim();

str= str +br.readLine().trim();//获取币种缩写

String patt = "

(.*)";

Pattern r=Pattern.compile(patt);

Matcher m=r.matcher(str);//matchStr = m.group(1);//将汉字与缩写进行分离//matchStr = (matchStr.split())[1];

if(m.find()) {

matchStr= m.group(1);

matchStr= (matchStr.split(" "))[1];

System.out.println(matchStr);

}else{

System.out.println("No Match");

}for (int i = 0; i < RateInfo.NELEM; i++) {

str=br.readLine();

String pattE= "

(.*?) ";

r=Pattern.compile(pattE);

m=r.matcher(str);if(m.find())

System.out.println(m.group(1));elseSystem.out.println("No Match");

}

}

}

input.close();

}//设置不同货币之间的利率//1 $from * $rate = 1 $to

public static void setRate(String from, String to, doublerate) {

rateTable.put(from+to, newDouble(rate));

}public staticDouble getRate(String from, String to) {return 615.65;//return (Double) rateTable.get(from + to);

}//将一定量的货币$m, 转变成单位为$to的货币量//return: 相应的货币值

public staticMoney exchangeRate(Money m, String to) {if (m.unit.equals(to)) return newMoney(m);

Double rate=getRate(m.unit, to);if (rate == null) {throw newIllegalArgumentException();

}return new Money(m.amount*rate.doubleValue(), to);

}

}

THE END

发表回复