这道题,让我一开始就想用“Java 的方式”去写,呵呵,所以就建了一个新类去处理它。
然后用到一些枚举类的特性,如 Enum.ordinal() 来获得枚举类的位置信息,Enum.values()[Enum.ordinal()] 来反向获得一个数值所对应的枚举类型。这样,就巧妙的借助枚举类来处理了月份。
本来想实现一个更完整的 MayaCalendar 类,不过考虑与本题无关,且有些算法没弄明白,所以暂时放弃了。在“问答”处提了个问题,是我期望解决但一时没解决的问题。希望有高手能帮忙解答一下,谢谢。
本题代码如下:
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public void run() throws Exception {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
scan.nextLine();
System.out.println(n);
while (n-- > 0) {
int day = (int) scan.nextDouble(); // 此处故意将输入理解为 double,免去了转换的过程
String mon = scan.next();
int year = scan.nextInt();
scan.nextLine();
MayaCalendar mc = new MayaCalendar(day, mon, year);
System.out.println(mc.getTzolkin());
}
}
public static void main(String[] args) {
Main m = new Main();
try {
m.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class MayaCalendar {
private long days;
public MayaCalendar(int day, String mon, int year) {
this(day, Haab.valueOf(mon).ordinal(), year);
}
/**
* Parse Haab calendar.
* TODO Error check.
*
* @param day base on 0
* @param mon base on 0
* @param year base on 0
*/
public MayaCalendar(int day, int mon, int year) {
days = 1; // all input is 0, means one day.
days += day;
days += mon * 20;
days += year * 365;
}
public String getTzolkin() {
StringBuffer sb = new StringBuffer();
int num = (int) days % 13;
if (num == 0) num = 13;
sb.append(num);
sb.append(" ");
int token = (int) days % 20;
if (token == 0) token = 20;
sb.append(Tzolkin.values()[token - 1]);
sb.append(" ");
int year = (int) Math.ceil(days / 260f);
sb.append(year - 1);
return sb.toString();
}
public long getDays() {
return days;
}
}
enum Haab {
pop, no, zip, zotz, tzec, xul, yoxkin, mol, chen, yax, zac, ceh, mac, kankin, muan, pax, koyab, cumhu, uayet;
}
enum Tzolkin {
imix, ik, akbal, kan, chicchan, cimi, manik, lamat, muluk, ok, chuen, eb, ben, ix, mem, cib, caban, eznab, canac, ahau;
}