Table of Contents
1 问题描述
2 类设计
3 初步实现
3.1 建立项目目录结构
3.2 建立测试文件
3.3 对应的实现文件, Money
3.4 增加输入输出: 一般化
3.5 对应的实现, MoneyDemo
3.6 小结
4 进一步的改进
4.1 输入格式统一以及错误处理
4.2 调用最新的汇率信息
1 问题描述
实现不同货币之间的汇率换算.
名词: 货币, 汇率
动词: 换算
2 类设计
class list:
Money
double amount: 货币的数量
String unit: 货币的单位
Rate
private Hashtable rateTable: 用来存储不同货币之间的汇率
3 初步实现
3.1 建立项目目录结构
.
├── build.xml
├── lib
│ ├── hamcrest-core.jar
│ └── junit.jar
├── README.txt
├── run
└── src
└── com
└── cnblogs
└── grassandmoon
其中, build.xml为ant执行所需的配置文件. run为shell文件, 用于运行编译后的java程序.
build.xml文件内容如下:
复制代码
1 < xml version="1.0" >
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 destdir="${build.classes}"
28 classpath="${java.lib}:${lib.dir}/junit.jar:${build.classses}"
29 debug="on"
30 includeantruntime="on"/>
31
32
33
34
35
36
复制代码
3.2 建立测试文件
复制代码
/** TestRate.java
* 用于货币汇率转换工具的测试
*/
package com.cnblogs.grassandmoon;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class TestRate {
@Test
public void testGetRate() {
Money m = new Money(150, "USD");
Rate.setRate("USD", "CNY", 6.25);
Money mCNY = Rate.exchangeRate(m, "CNY");
assertEqual(new Money(150*6.25, "CNY"), mCNY);
}
}
复制代码
3.3 对应的实现文件, Money
复制代码
package com.cnblogs.grassandmoon;
import java.util.*;
class Rate {
// 利用hashtable对不同货币之间的利率进行存储
// key: $from+$to, value: $rate
private static Hashtable rateTable = new Hashtable();
// 设置不同货币之间的利率
// 1 $from * $rate = 1 $to
public static void setRate(String from, String to, double rate) {
rateTable.put(from+to, new Double(rate));
}
private static double getRate(String key) {
Double db = (Double) rateTable.get(key);
return db.doubleva lue();
}
// 将一定量的货币$m, 转变成单位为$to的货币量
// return: 相应的货币值
public static Money exchangeRate(Money m, String to) {
if (m.unit == to) return new Money(m);
String key = m.unit + to;
double rate = getRate(key);
return new Money(m.amount*rate, to);
}
}
public class Money {
double amount;
String unit;
public Money(double amount, String unit) {
setMoney(amount, unit);
}
public Money(Money m) {
setMoney(m.amount, m.unit);
}
public void setMoney(double amount, String unit) {
this.amount = amount;
this.unit = unit;
}
public boolean equals(Object obj) {
Money other = (Money) obj;
return amount == other.amount
&& unit.equals(other.unit);
}
}
复制代码
3.4 增加输入输出: 一般化
有哪些内容需要进行输入输出呢
输入
欢迎信息
欢迎使用汇率转换器
版本: 1.0
作者: 钟谢伟
帮助信息
1. 输入不同货币以及对应的汇率信息,
第一个为需要转换的货币单位
第二个为转换到的目标货币单位
第三个为相应的汇率
不同项目之间用空格隔开
如: USD CNY 6.25
表示: 1 USD * 6.25 = 1 CNY
2. 输入待转换量, 用空格隔开
如: 150 USD
3. 帮助
4. 退