问题描述
- JAVA中如何计数或如何进行标记
-
例如我要计算出2015-1900,年之间所有闰年的个数或标记出闰年,该利用哪些代码完成
解决方案
public class SelectSort {
public static void main(String[] args) throws IOException{
for (int i = 1900; i <= 2015; i++) {
if(i%100==0){
if(i%400==0){
System.out.println(i+"是闰年");
}
}else{
if(i%4==0){
System.out.println(i+"是闰年");
}
}
}
}
}
解决方案二:
public class RunNian {
private int startYear = 0;
private int endYear = 0;
private ArrayList<String> runnianList = new ArrayList();
public RunNian(int startYear,int endYear){
this.startYear = startYear;
this.endYear = endYear;
}
public void cal(){
for(int year = startYear;year<=endYear;year++){
if((year%4==0&&year%100!=0)||year%400==0){
runnianList.add(year+"");
}
}
}
public int getCount(){
return this.runnianList.size();
}
public void printRN(){
for(int i=0;i<this.runnianList.size();i++){
System.out.println(this.runnianList.get(i));
}
}
/**
* @param args
*/
public static void main(String[] args) {
RunNian rn = new RunNian(1900,2015);
rn.cal();
System.out.println("润年数量:"+rn.getCount());
System.out.println("润年列表:");
rn.printRN();
}
}
如果有帮助,顺手采纳一下哦
解决方案三:
建个栈,是闰年就进栈,数据,列表同理
解决方案四:
我是使用List来存放所有的闰年,而判断闰年的方式是根据Calendar的属性来进行判断,代码比较短,请参考:
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* 主要是求闰年方法的一种演示,可以通过判断每年的最后一天是否是第366天来进行闰年的判断
*/
public class LeapYearDemo {
public static void main(String[] args) {
int startYear = 1900;
int endYear = 2015;
List<Integer> leapYearList = getLeapYearList(startYear, endYear);
System.out.println("起始年份(包含)" + startYear + "-截止年份(包含)" + endYear
+ "之间的闰年年份共有" + leapYearList.size() + "个,分别是:");
for (Integer leapYear : leapYearList) {
System.out.print(leapYear + "t");
}
}
/**
* 获取给定年份之间的所有闰年年份,包含起始和截止年份
* <p>
* 主要通过Calendar类的DAY_OF_YEAR属性来判断每年的最后一天是否是第366天
*
* @param startYear
* @param endYear
* @return
*/
private static List<Integer> getLeapYearList(int startYear, int endYear) {
List<Integer> leapYearList = new ArrayList<Integer>();
// 获取当前日期,无所谓,后面会改为12月31日,循环中改年份
Calendar _cal = Calendar.getInstance();
_cal.set(Calendar.MONTH, 11);
_cal.set(Calendar.DAY_OF_MONTH, 31);
for (int i = startYear; i <= endYear; i++) {
_cal.set(Calendar.YEAR, i);
if (_cal.get(Calendar.DAY_OF_YEAR) == 366) {
leapYearList.add(i);
}
}
return leapYearList;
}
}
运行结果:
起始年份(包含)1900-截止年份(包含)2015之间的闰年年份共有28个,分别是:
1904 1908 1912 1916 1920 1924 1928 1932 1936 1940 1944 1948 1952 1956 1960 1964 1968 1972 1976 1980 1984 1988 1992 1996 2000 2004 2008 2012
解决方案六:
简单的话就用两个数组来分别存放,先进行判断
解决方案七:
public class SelectSort {
public static void main(String[] args) throws IOException{
for (int i = 1900; i <= 2015; i++) {
if(i%100==0){
if(i%400==0){
System.out.println(i+"是闰年");
}
}else{
if(i%4==0){
System.out.println(i+"是闰年");
}
}
}
}
}