已知天干地支,求对应的数值。拒绝查表法,最好有Java代码。
谢谢
如,
已知 甲子 求得结果 1
已知 壬辰 求得结果 29
已知天干地支,求对应的数值。拒绝查表法,最好有Java代码。
谢谢
如,
已知 甲子 求得结果 1
已知 壬辰 求得结果 29
我写了个,[code="java"]
import java.util.HashMap;
public class ChineseCalendar {
private final static HashMap Heavenly_Stems = new HashMap();
private final static HashMap Earthly_Branches = new HashMap();
static {
Heavenly_Stems.put('甲', 1);
Heavenly_Stems.put('乙', 2);
Heavenly_Stems.put('丙', 3);
Heavenly_Stems.put('丁', 4);
Heavenly_Stems.put('戊', 5);
Heavenly_Stems.put('己', 6);
Heavenly_Stems.put('庚', 7);
Heavenly_Stems.put('辛', 8);
Heavenly_Stems.put('壬', 9);
Heavenly_Stems.put('癸', 10);
Earthly_Branches.put('子', 1);
Earthly_Branches.put('丑', 2);
Earthly_Branches.put('寅', 3);
Earthly_Branches.put('卯', 4);
Earthly_Branches.put('辰', 5);
Earthly_Branches.put('巳', 6);
Earthly_Branches.put('午', 7);
Earthly_Branches.put('未', 8);
Earthly_Branches.put('申', 9);
Earthly_Branches.put('酉', 10);
Earthly_Branches.put('戌', 11);
Earthly_Branches.put('亥', 12);
}
public static int getCode(String name) {
int n = name.length();
if (n < 2)
throw new IllegalArgumentException("Unknown name: " + name);
char h = name.charAt(0);
Integer hCode = Heavenly_Stems.get(h);
if (hCode == null)
throw new IllegalArgumentException("Unknown name: " + name);
char e = name.charAt(1);
Integer eCode = Earthly_Branches.get(e);
if (eCode == null)
throw new IllegalArgumentException("Unknown name: " + name);
hCode%=10;
eCode%=12;
for (int c = 1; c <= 60; c++) {
if (c % 10 == hCode && c % 12 == eCode)
return c;
}
throw new IllegalArgumentException("Unknown name: " + name);
}
public static void main(String[] args) {
System.out.println(getCode("甲子"));
System.out.println(getCode("壬辰"));
System.out.println(getCode("癸酉"));
System.out.println(getCode("癸亥"));
}
}
[/code]
其实用查表法是最好的