[java]干支纪年法(循环练习)
作者:互联网
干支纪年法属于上古以来中国纪年历法,其由十天干十二地支按照一定顺序结合来表示年份.
十天干分别为:
甲、乙、丙、丁、戊、己、庚、辛、壬、癸
十二地支分别为:
子、丑、寅、卯、辰、巳、午、未、申、酉、戌、亥
干支纪年基本规则:
甲子、乙丑......癸酉对应结束后此时应当对应甲戊,乙亥,丙子.........
以此类推,所以干支纪年法六十年一轮回.
当我们想要用循环输出一个轮回的干支纪年法的时候,基本思路如下:
1、创建两个数组分存放天干地支
2、使用for循环依次输出对应天干地支
代码如下:
public class practice {
public static void main(String[] args) {
String sky[] = {"甲","乙","丙","丁","戊","己","庚","辛","壬","癸"};
String land[] = {"子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"};
String[] array = new String[60];
int j = 0;
int freq = 0;
int k=0;
while(freq < 60){ //打印六十次
for(int i = 0;i < 10;i++){ //十天干
if(j == 12){ //十二地支,由于数组下标从0开始,所以当地支等于十二时归零
j = 0;
}
System.out.print(" "+sky[i]+land[j]+"年");
k++;
if(k==12){ //为方便检查,一行打印十二次后回车
System.out.println();
k=0;
}
freq++; //打印次数
j++;
}
}
}
结果如下:
特别注意的是当地支到11时就需要归零,否则打印时就会访问越界
下面看下如何输入一个年份判断其是什么年:
判断方法:
天干:用年份减3除10,取余数(余数1,2,3,4,5......9,0,分别对应甲,乙,丙,丁......癸)
地支:用年份减3除12,取余数(余数1,2,3,4,5......11,0,分别对应子,丑,寅,卯......亥)
代码如下:
import java.util.Scanner;
public class practice {
public static void main(String[] args) {
String sky[] = {"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"};
String land[] = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"};
Scanner scanner = new Scanner(System.in);
System.out.print("请输入年份:");
int input = scanner.nextInt();
int i = (input - 3) % 10; //计算天干
int j = (input - 3) % 12; //计算地支
if (i == 0) {
i = 10; //余数为0对应天干最后一个
}
if (j == 0) {
j = 12; //余数为0对应地支最后一个
}
System.out.println(input + "是" + sky[i - 1] + land[j - 1] + "年");
}
}
结果:
标签:12,java,String,纪年,System,int,余数,干支,地支 来源: https://blog.csdn.net/weixin_59094759/article/details/121447283