iteye_12376 2011-10-08 23:39
浏览 411
已采纳

求“天干地支”算法

已知天干地支,求对应的数值。拒绝查表法,最好有Java代码。
谢谢

如,
已知 甲子 求得结果 1
已知 壬辰 求得结果 29

  • 写回答

1条回答 默认 最新

  • _1_1_7_ 2011-10-09 09:27
    关注

    我写了个,[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]

    其实用查表法是最好的

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?